私は AngularJS を使用していますが、読み込みに時間がかかるモデルを適切にバインドできません。私は 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;
}]);
私の実際の ListService はこれよりもはるかに複雑ですが、関連する部分のみをコピーしたので、質問を明確に行うことができます。
私のコントローラーは ListController を呼び出し、「resolve」オプションを使用してルーターから「リスト」を取得します。
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
}]);
私の見解では:
<div class="item-wrapper"
ng-repeat="item in list.items">
{{item}}
</div>
私の問題は、アイテムがコントローラーにロードされた後、ビューにアイテムが表示されず、何も描画されないことです。$timeout と $rootScope.$apply で loadItems の成功メソッドをラップしようとしましたが、役に立ちません。それを解決する方法はありますか?
更新
@Chandermani のアドバイスに従い、コントローラーで実行しました。
list.loadItems().then(function() {
$scope.items = list.items;
});
項目はビューに読み込まれますが、_addItem() メソッドを使用して list.items を更新すると、何も起こらず、ビューに新しい項目が表示されないことがあります。次のように _addItem() を $timeout でラップしようとしましたが、どちらも役に立ちませんでした:
_addItem: function(item) {
$timeout(function() {
this.items || (this.items = []);
this.items.push(item);
});
}