Im pretty new to angularJS so please forgive me if I say anything completely wrong. I making some sort of a chat. I have a problem with the scope/view not beign updated after getting the data. I have a variable $scope.users which is an array containing infos about users and the view does an ng-repeat on the users to display their infos. The data is stored from a previous page and loaded through session storage. The controller looks like:
app.controller('table-controller',['$scope','$interval','HttpService','TableModel',
function($scope,$interval,HttpService,TableModel){
var _this = this;
console.log('loading table controller ...');
$scope.users = [];
var sessionData = JSON.parse(sessionStorage.getItem('sessionData'));
var activeUsers = sessionData.activeUsers;
//$scope.users = TableModel.initUsers();
$scope.$watch('users',function(){
for(var i = 0; i < 10; i++){
$scope.users.push({
user : ' ',
name : 'Vacant',
picture : '../img/sit_default.png',
speak_turn : ' ',
sit : i,
last_request : 0
});
}
for(var i = 0; i < activeUsers.length; i++){
var sit = activeUsers[i].sit;
$scope.users[sit] = activeUsers[i];
}
});
$scope.className = function(index){
return "sit" + (index + 1);
}
And the html is :
<ul class="first-place">
<li ng-repeat="user in users track by $index" ng-class="className($index)">
<div class="pro_pic_wrap">
<img ng-src="{{user.picture}}" alt="">
<span>{{$index + 1}}</span>
</div>
<a href="#">{{user.name}}</a>
</li>
</ul>
Everything works fine if I use $watch to create $scope.users. Otherwise when the page loads the view sees an empty $scope.users so ng-repeat does nothing. If i reload the page everything works fine. I tried $scope.$apply() but gives me an error saying digest is already being called. I dont understand why I need to use $watch here. Thanks in advance for your help!
var users = sessionData.users;should it be the $scope.users?