I am using AngularJS and I don't manage to bind properly models that need time to load. I have this service called ListService:
angular.module('3pix').factory('ListService', ['$q', '$timeout', 'underscore', 'Item', 'ItemResource',
function ($q, $timeout, _, Item, ItemResource) {
var List = function () {
};
_.extend(List.prototype, {
_addItem: function(item) {
this.items || (this.items = []);
this.items.push(item);
},
loadItems: function() {
var scope = this;
var deferred = $q.defer();
ItemResource.get_items({id: 39}, function(itemsData) {
itemsData.forEach(function(itemData) {
scope._addItem(new Item(itemData));
});
deferred.resolve(scope.items);
});
return deferred.promise;
}
});
return List;
}]);
My real ListService is far more complicated than this but I copied only the relevant parts so I can ask my question clearly.
My controller called ListController and it gets a 'list' from the router using 'resolve' option:
angular.module('3pix').controller('ListController', ['$scope', 'jquery', 'list',
function ($scope, $, list) {
$scope.list = list; //<-------- Here I got the list, I get it fine from the router
list.loadItems(); //<------- Here I load the list's items
}]);
In my view I have:
<div class="item-wrapper"
ng-repeat="item in list.items">
{{item}}
</div>
My problem is that after the items are loaded in the controller, the view doesn't displays the items and keeps drawing nothing. I tried to wrap the loadItems's success method in $timeout and $rootScope.$apply but it doesn't help. Any idea how to solve it?
UPDATE
I followed the advice of @Chandermani and I did in my controller:
list.loadItems().then(function() {
$scope.items = list.items;
});
The items are loaded in the view, but still, sometimes, when I update list.items using _addItem() method, nothing happen and the view doesn't show the new items. I tried to wrap _addItem() with $timeout as follows but it didn't helped either:
_addItem: function(item) {
$timeout(function() {
this.items || (this.items = []);
this.items.push(item);
});
}