将ng repeat与指令一起使用会导致子指令不更新

using ng-repeat with directives causes child directives not to update

本文关键字:指令 更新 repeat ng 一起      更新时间:2023-09-26

因此,如果在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