为ng重复刷新$ scope

时间:2014-05-18 14:58:17

标签: ajax angularjs

我正在使用twitch api制作Angular应用程序。在异步ajax调用之后,我必须做些什么来刷新重复范围($ scope.players)?

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;
        }
    }
}
});

1 个答案:

答案 0 :(得分:2)

ngRepeat指令有自己的观察者,您不需要关心模型更新。但请确保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;
        }
    }
  }