Reputation: 201
I am making an Angular App with using twitch api. What I must to do for refreshing ng repeat scope($scope.players), after async ajax call?
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;
}
}
}
});
Upvotes: 0
Views: 68
Reputation: 77904
ngRepeat
directive has own watchers and you don't need to care about model update. However be sure that getPlayer
fires digest cycle.
I suggest you helper factory that should check if digest cycle is running:
app.factory('UtilsFactory', ['$rootScope' function($rootScope) {
return {
isScopeInCycle: function() {
return $rootScope.$root.$$phase != '$apply' &&
$rootScope.$root.$$phase != '$digest';
}
}
The usage:
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;
}
}
}
Upvotes: 2