使用ng-repeat with directives会导致子指令不更新

时间:2016-01-07 16:07:59

标签: javascript angularjs angularjs-directive angularjs-ng-repeat

所以如果在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。你需要做的就是删除其中一个首要元素。有谁知道是什么原因造成这种情况以及如何解决它?

旁注:

我认为提及当在儿童中使用可编辑元素(如文本框)的稍微不同的情况下使用它时,数据绑定从子节点到父节点也是有用的。因此,将附加到控制器的变量分配给从该方向工作的父级的范围变量。这似乎是我遇到的从父母到孩子的唯一情况,那就是不起作用。

2 个答案:

答案 0 :(得分:1)

变化:

template:"<div>{{child.parent}}</div>",
controller:['$scope',function($scope){ this.parent=$scope.parent; }]

要:

template:"<div>{{parent}}</div>"
controller:function(){ }

由于您使用的是controllerAs语法,因此您不需要$ scope注入。 对于预期的绑定工作,你不要使用child.parent,只使用parent(或者你在控制器上的这个上下文注入的任何内容)

答案 1 :(得分:1)

我在$ compile服务中找到了一个修复此问题的属性。将属性bindToController:true添加到指令会获取scope属性中定义的所有变量并将它们附加到控制器,而不是范围本身意味着2路数据绑定是控制器上的变量而不是变量on范围。所以最终结果有这些变化

指令定义中的

scope:{
    parent:"=scope"
},
bindToController:true,

并在控制器中删除this.parent=$scope.parent

这是一个updated jsfiddle