我在服务中有一个创建函数,它负责获取输入数据、将其转换为资源、进行保存并将其插入本地缓存。
create = (data, success, error) ->
throw new Error("Unable to create new user, no company id exists") unless $resource_companies.id()
# create the resource
new_model = new resource(data)
# manually add the company id into the payload (TODO: company id should be inferred from the URL)
new_model.company_id = $resource_companies.id()
# do the save and callbacks
new_model.$save( () ->
list.push(new_model)
success.call(@) if success?
, error)
我的问题是监视列表变量的 ng:repeat 没有得到更新。据我所知,这不是在 AngularJS 外部发生的,因此它不需要 $scope.$apply() 来保持最新状态(实际上,如果我尝试触发摘要,我会得到一个已经在进行中的摘要错误)
更奇怪的是,我在其他地方使用了完全相同的模式,没有任何问题。
我的 Controller 用来访问列表数组的代码是(这个在服务中)
# refreshes the users in the system
refresh = (cb) -> list = resource.query( () -> cb.call(@) if cb? )
在 Controller 中:
$scope.users = $resource_users.refresh()
最佳答案
这可能是因为您正在分配一个新的引用。 Angular 正在观察旧的引用,它永远不会改变。这是引用被替换的地方:
list = resource.query( /* ... */ )
相反,如果您将列表设为对象的属性,angular 的 ng-repeat watch 应该能够观察到 data
的 list
属性的变化对象:
data.list = resource.query( /* ... */ )
关于AngularJS array.push ng :repeat not updating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17055945/