将ng repeat与指令一起使用会导致子指令不更新
using ng-repeat with directives causes child directives not to update
因此,如果在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。你所要做的就是删除第一个元素。有人知道是什么原因造成的以及如何解决吗?
旁注:
我还认为,当在一个稍微不同的情况下使用它时,如果子对象中有可编辑元素(如文本框),数据绑定从子对象到父对象,这可能会很有用。因此,将一个附加到控制器的变量分配给来自父级的作用域变量是朝着这个方向进行的。这似乎是我遇到的唯一一种情况,从父母到孩子,这是不起作用的。
更改:
template:"<div>{{child.parent}}</div>",
controller:['$scope',function($scope){ this.parent=$scope.parent; }]
收件人:
template:"<div>{{parent}}</div>"
controller:function(){ }
由于您使用的是controllerAs语法,因此不需要$scope注入。对于预期的绑定工作,您不使用child.parent,只使用parent(或在控制器上的上下文中注入的任何内容)
我在$compile服务中发现了一个修复此问题的属性。将属性bindToController:true
添加到指令会获取scope属性中定义的所有变量,并将它们附加到控制器,而不是作用域本身,这意味着双向数据绑定是到控制器上的变量,而不是范围上的变量。所以最终结果是发生了这些变化
在您的指令定义中
scope:{
parent:"=scope"
},
bindToController:true,
并且在控制器中移除this.parent=$scope.parent
这是一个更新的jsfiddle
相关文章:
- 对父作用域的指令更新延迟了一步
- 我无法通过angularjs中的指令更新变量
- AngularJs 指令更新
- 如何在事件上对jquery上的ng模型进行指令更新
- 可以从控制器更新工厂,但不能从指令更新
- Angular指令更新多个元素的高度以匹配最高的
- Angular.js-从指令更新父作用域
- Angularjs 指令更新到 DOM 属性值的变化
- 从使用它的指令更新服务
- 推送到数组不会通过ng repeat指令更新视图列表
- AngularJS-通过服务从指令更新控制器数据(this.model语法)
- 如何让AngularJS指令更新由另一个指令生成的锚点
- 如何使用选择列表从指令更新父级上的模型
- 根据AngularJS中$apply或$digest循环的指令更新模型
- 从指令更新作用域,并使用另一个指令进行监视
- 通过指令更新作用域.最佳实践
- AngularJS后台任务指令更新控制器
- Angular指令更新父控制器对象
- 美元范围.父母.messageContent=值没有从指令更新父作用域
- AngularJS:通过指令更新模板绑定