【发布时间】:2016-01-08 03:32:40
【问题描述】:
所以如果在 angular.js 中发现了这个非常有趣的错误。如果您在 ng-repeat 中有一个自定义指令正在主动更改指令中的变量,则不要更新。意思是如果我的数组中有 3 个元素用于 ng-repeat 它初始化就好了但是如果我从数组中删除元素 1 元素 1 传递给其子指令的任何变量以某种方式最终在元素 2 的子指令中这是我的示例代码.
<div ng-app='testing'>
<div ng-controller='testing as test'>
<div ng-repeat='item in test.example track by $index'>
{{item.title}}
<child scope='item.data'></child>
<button ng-click="test.delete($index)">
Delete
</button>
</div>
</div>
</div>
然后在我的 js 文件中
console.log('hello world');
var app=angular.module('testing',['testingChild']);
app.controller('testing',[function(){
this.example=[{
title:"this is the first title",
data:"this is the first index"
},{
title:"this is the second title",
data:"this is the second index"
},{
title:"this is the third title",
data:"this is the third index"
}];
this.delete=function(index){
this.example.splice(index,1);
};
}]);
var child=angular.module('testingChild',[]);
child.directive('child',[function(){
return{
restrict:"E",
scope:{
parent:"=scope"
},
template:"<div>{{child.parent}}</div>",
controller:['$scope',function($scope){
this.parent=$scope.parent;
}],
controllerAs:"child"
};
}]);
我有一个正常工作的jsfiddle here。你所要做的就是删除第一个元素。有谁知道这是什么原因以及如何解决它?
旁注:
我认为在稍微不同的情况下使用子元素(如文本框)中的可编辑元素时,我认为它可能很有用,数据绑定从子元素到父元素。因此,将附加到控制器的变量分配给父级的作用域变量就是朝这个方向工作的。这似乎是我遇到的唯一一种从父母到孩子的情况,这是行不通的。
【问题讨论】:
-
如果您格式化您的代码,您将更有可能得到答案。
-
这正是我命名它的原因,因为它包含的指令是我描述的情况下父级的子级。在我的非简化代码中,它们位于单独的文件中,因此每个文件都需要自己的模块。
标签: javascript angularjs angularjs-directive angularjs-ng-repeat