我正在使用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;
}
}
}
});
答案 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;
}
}
}