除了从数据库中获取整个数组时,Ng-repeat在视图中不会更新

时间:2017-09-10 08:29:19

标签: angularjs angularjs-ng-repeat angularjs-service

角度ng-repeat无法正确更新的问题似乎很常见,并且问题已经有很多线程。然而对我来说,它在某些情况下是有效的,而在其他一些非常奇怪的情况下,SO上的其他任何解决方案都无法正常工作。

所以我有以下html:

<div ng-init="vm.loadItems()" ng-controller="itemController as vm">
 <div ng-repeat="item in vm.items>
  {{item.name}}
 </div>
 <form ng-submit="vm.submitItem()">
  <input type="text" ng-model="vm.item.name">
 <button>Create new</button>
 </form>
</div>

控制器:

angular.module('app',[]).controller('itemController',function($scope, itemsService){

 vm.items = [];
 vm.item = { name : "" };

 vm.loadItems = function(){
  itemsService
   .getAll()
   .then(function(response){
    vm.items = response.data;
   });
 }

 vm.submitItem = function(){
  itemsService
   .createNew(vm.item)
   .then(function(response){
    var newItems = vm.items;
    newItems.push(response.data);
    vm.items = newItems;
    console.log(vm.items)
   });
 }
});

使用的服务itemsService使用的getAll() GET使用createNew()请求返回数据库中的所有项目,POST使用vm.loadItems()创建数据库中的新项目vm.submitItem()请求,然后返回创建的项目。

加载页面后,使用vm.submitItem = function(){ itemsService .createNew(vm.item) .then(function(){ vm.loadItems(); }); } 正确更新了项目,但是当我在$scope.$apply()中推送新项目时,视图不会更改。我可以通过使用

来解决这个问题
$digest already in progress

但是这会给后端创建一个非常不受欢迎的第二个请求。 我尝试使用$timeout(function(){ vm.items = newItems; }); ,但收到错误FormRequest。使用

protected function failedAuthorization()
{
    throw new AuthorizationException('Your new message goes here.');
}

也不起作用。

如何解决这个问题的任何想法都非常感谢!

1 个答案:

答案 0 :(得分:0)

这是我的救援! :)

您的问题是,在分配新对象时,您正在破坏ng-repeat和vm.items之间的引用。因此,解决问题的方法是改变&#34; .then&#34;创建新项目时的方法。看一看! :)

vm.submitItem = function(){
  itemsService
  .createNew(vm.item)
  .then(function(response){
    vm.items.push(response.data);
    console.log(vm.items);
  });
}

减少线条,解决问题! ^^