2014-05-18 73 views
0

我正在使用twitch api製作一個Angular App。在異步ajax調用之後,我必須做些什麼來刷新重複範圍($ scope.players)?刷新ng範圍爲ng repeat

app.controller('MainCtrl', function($scope,TwitchFactory) { 
$scope.channels = channels; 
$scope.players = []; 
handlePlayers(); 

function handlePlayers() { 
    var player; 

    var length = channels.length; 
    for (var i = 0; i < length; ++i) { 
     switch (channels[i].serviceId) { 
     case '3': 
      TwitchFactory.getPlayer(channels[i]).done(function(data) { 
       if(data.stream) { 
        player = {}; 
        player.game = data.stream.game; 

        $scope.players.push(player); 
       } 
      }); 
     break; 
     } 
    } 
} 
}); 

回答

2

ngRepeatngRepeat指令擁有自己的監視器,您無需關心模型更新。但可以肯定的是,getPlayer火災消化週期。

我建議你幫手工廠,應檢查是否消化週期運行:

app.factory('UtilsFactory', ['$rootScope' function($rootScope) { 

     return { 
      isScopeInCycle: function() { 
       return $rootScope.$root.$$phase != '$apply' && 
         $rootScope.$root.$$phase != '$digest'; 
      } 
} 

用法:

  • 附加工廠控制器和使用:

function handlePlayers() { 
    var player; 

    var length = channels.length; 
    for (var i = 0; i < length; ++i) { 
     switch (channels[i].serviceId) { 
     case '3': 
      TwitchFactory.getPlayer(channels[i]).done(function(data) { 
       if(data.stream) { 
        player = {}; 
        player.game = data.stream.game; 

        $scope.players.push(player); 

        if (UtilsFactory.isScopeInCycle()) { 
         $rootScope.$apply(function() {      
         $scope.players.push(player); 

         }); 
         } 
         else{ 
         $scope.players.push(player); 
         } 
       } 
      }); 
     break; 
     } 
    } 
    } 
+0

謝謝。他沒有更新模型的原因? – YYY

+0

'$ apply'有幫助嗎? –

+0

是的。這有幫助。 – YYY