Javascript 角度js模型不';束缚
我使用的是AngularJS,无法正确绑定需要时间加载的模型。我有一个名为ListService的服务:Javascript 角度js模型不';束缚,javascript,angularjs,Javascript,Angularjs,我使用的是AngularJS,无法正确绑定需要时间加载的模型。我有一个名为ListService的服务: angular.module('3pix').factory('ListService', ['$q', '$timeout', 'underscore', 'Item', 'ItemResource', function ($q, $timeout, _, Item, ItemResource) { var List = function () {
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;
}]);
我的real ListService远比这复杂,但我只复制了相关部分,这样我就可以清楚地提问了。我的控制器名为ListController,它使用“解析”选项从路由器获取“列表”:
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
}]);
项目会加载到视图中,但有时,当我使用_addItem()方法更新list.items时,不会发生任何事情,视图也不会显示新项目。我尝试用$timeout包装_addItem(),如下所示,但也没有帮助:
_addItem: function(item) {
$timeout(function() {
this.items || (this.items = []);
this.items.push(item);
});
}
我认为问题在于您正在将作用域列表分配给服务实例,而不是方法结果 换成
angular.module('3pix').controller('ListController', ['$scope', 'jquery', 'list',
function ($scope, $, list) {
$scope.list = list.loadItems()
}]);
你也可以用html试试这个吗
ng-repeat="item in list"
既然您正在返回承诺,那么您在控制器中的then语句在哪里???@Ajaybeniwal:控制器中的语句应该是什么?List.items是更改,它不应该影响控制器的List.item?List还包含我在视图中需要的其他属性。在我的问题中,我将类缩减为必要的类型。您仍然可以使用list服务变量。您定义的
列表
服务不包含任何要绑定到的items属性。因此,您要么绑定承诺,要么绑定使用承诺上的然后方法检索的返回值。我不希望在控制器上添加属性,因为我在列表服务中已经有此属性。除此之外,List还有其他添加项的方法。还有其他方法吗?我不是说在controller上添加任何属性,但是您注入的服务没有您试图在视图中绑定的属性项
。服务有属性项:List.items保存这些项。
angular.module('3pix').controller('ListController', ['$scope', 'jquery', 'list',
function ($scope, $, list) {
$scope.list = list.loadItems()
}]);
ng-repeat="item in list"