简体   繁体   English

AngularJS:使用ngRepeat和ngInit从列表中删除项目

[英]AngularJS: remove item from a list using ngRepeat and ngInit

I use ngRepeat to show items from a list. 我使用ngRepeat来显示列表中的项目。 As recommended by the documentation, I use ngInit to assign the $index variable to an "itemIndex" variable that I refer to inside the loop. 根据文档的建议,我使用ngInit将$ index变量赋值给我在循环内引用的“itemIndex”变量。 Every item is shown with a button that allows me to remove it from the list. 每个项目都显示一个按钮,允许我从列表中删除它。 Here is an example jsfiddle: 是一个jsfiddle示例:

<li ng-repeat="item in list" ng-init="itemIndex = $index"> {{itemIndex}} {{item}} <a href="#" ng-click="removeItem(itemIndex)">remove</a></li>

If I try to remove an item, the itemIndex variable is not updated, so subsequent removals fail. 如果我尝试删除项目,则不更新itemIndex变量,因此后续删除失败。 Instead, if i use the $index variable, everything works as expected ( here is the same example without the ngInit-ed variable): 相反,如果我使用$ index变量,一切都按预期工作( 是没有ngInit-ed变量的相同示例):

<li ng-repeat="item in list">{{$index}} - {{item}} <a href="#" ng-click="removeItem($index)">remove</a></li>

Is this a bug or it is an intended behavior? 这是一个错误还是预期的行为?

This behaviour is intended, ng-init purposely runs only once. 这种行为是有意的,ng-init只是故意运行一次。

When you look at the ngInit directive, ( https://github.com/angular/angular.js/blob/master/src/ng/directive/ngInit.js ) you can see that the $eval uation of the script passed to ng-init is done in the compile function instead of the link function. 当您查看ngInit指令( https://github.com/angular/angular.js/blob/master/src/ng/directive/ngInit.js )时,您可以看到脚本的$eval uation传递给ng-init在compile函数中完成,而不是在link函数中完成。

var ngInitDirective = ngDirective({
  priority: 450,
  compile: function() {
    return {
      pre: function(scope, element, attrs) {
        scope.$eval(attrs.ngInit);
      }
    };
  }
});

Compile is only executed only once in your applications lifetime, whereas link is executed every time the directive is link ed to an element/your document. 编译仅在应用程序生命周期中执行一次,而每次将指令link到元素/文档时都会执行link

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM