0

我正在使用 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>

我的问题是,在控制器中加载项目后,视图不显示项目并且不绘制任何内容。我试图将 loadItems 的成功方法包装在 $timeout 和 $rootScope.$apply 中,但它没有帮助。知道如何解决吗?

更新
我遵循了@Chandermani 的建议,并在我的控制器中做了:

list.loadItems().then(function() {
    $scope.items = list.items;
});

项目已加载到视图中,但有时,当我使用 _addItem() 方法更新 list.items 时,什么也没有发生,视图也不会显示新项目。我试图用 $timeout 包装 _addItem() 如下,但它也没有帮助:

  _addItem: function(item) {
        $timeout(function() {
            this.items || (this.items = []);
            this.items.push(item);
        });
    }
4

1 回答 1

1

我认为问题在于您将范围列表分配给服务实例而不是方法结果。

将其更改为

angular.module('3pix').controller('ListController', ['$scope', 'jquery', 'list',
    function ($scope, $, list) {
        $scope.list = list.loadItems()
}]);

你也可以在html中试试这个

ng-repeat="item in list"
于 2013-07-29T07:49:13.787 回答