从$ rootScope数组中删除ngRepeat项目不会立即从html

时间:2015-07-08 13:59:15

标签: javascript angularjs

尝试使用angular从 ul 中删除 li ,从数组中成功删除元素但angularJS不会删除 li 直到它悬停在某个特定 li 上的某些操作。代码如下:

app.js

myApp.run(function($rootScope, appAPIservice){ 
  appAPIservice.getInterests().success(function (response) {
    $rootScope.interests = [];
    if (response.data) {
      var interests = response.data;
      for (var i = 0; i < interests.length; i++) {
        $rootScope.interests.push(interests[i]));
      }
    }
  });
});

的index.html

<ul ng-controller="interestsController">   
  <li ng-repeat="interest in interests">
    <a href="#{{interest.link}}">{{interest.parentName}} / {{interest.childName}}</a>
    <button ng-click="deleteInterest($index)"></button>
  </li>
</ul>

controllers.js :此处定义了deleteInterest

myApp.controller('interestsController', function($scope) {
  $scope.deleteInterest = function(arrayIndex) {
          $scope.interests.splice(arrayIndex, 1);
      });
  }
});

这会在页面加载时产生以下输出:

<ul class="ng-scope" ng-controller="interestsController">   
  <li class="ng-scope" ng-repeat="interest in interests">
    <a href="#/other-link class="ng-binding">Other Parent/Other Child</a>
    <button ng-click="deleteInterest($index)"><i class="icon-close"></i></button>
  </li>
</ul>

单击deleteInterest()按钮时会出现问题。以下类将添加到列表项类:ng-animate,ng-leave,ng-leave-active。不幸的是,列表项仍保留在列表中,直到该项目悬停在上。此时,列表项已成功从DOM中删除。

<li class="ng-scope ng-animate ng-leave ng-leave-active" ng-repeat="interest in interests">
  <a href="#/some-link" class="ng-binding">Some Parent / Some Child </a>
  <button ng-click="deleteInterest($index)"><i class="icon-close"></i></button>
</li>

我试过包装interestsController.deleteInterest的
$scope.interests.splice(arrayIndex, 1);

$scope.$apply(function(){ 
  $scope.interests.splice(arrayIndex, 1);
}); 

但是我收到一条错误消息,说$ scope。$ digest已在进行中。

有没有办法强制angularJS删除所有ng-leave项?

2 个答案:

答案 0 :(得分:0)

一些想法。而不是$scope.$apply,请尝试

$timeout(function(){ 
  $scope.interests.splice(arrayIndex, 1);
});

$ timeout将在必要时内部触发摘要,但如果摘要已在进行中,则不会抛出该错误。

或者,如何使用CSS来隐藏li直到角度变为圆形以移除它?

.ng-leave { display:none; }

答案 1 :(得分:0)

我对ng-repeat有类似的问题。 将项目数组长度设置为0后,我必须运行超时延迟:

$timeout(function(){ 
  do_some_action
}, 2000);

即使evalAsync也不起作用:

$scope.$evalAsync(function () {
   do_some_action
});

另一种解决方法是不考虑旧项目:

var elems = angular.element(document.getElementsByClassName('repeated_items'));
_.each(elems, function (itm) {
   if (itm.$$hashKey) return true;
   do_some_action
});