【问题标题】:using ng-repeat with directives causes child directives not to update将 ng-repeat 与指令一起使用会导致子指令不更新
【发布时间】: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


【解决方案1】:

变化:

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

收件人:

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

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

【讨论】:

  • 为什么第一种方法行不通?角度数据绑定理论上应该更新。
  • 因为其他原因,将数据附加到控制器可能很有用。
  • 如果只是范围问题,我什至不确定为什么将元素 1 中的变量首先传递给元素 2。
  • 是的,第一种方法应该可以工作,但是你看,在指令中使用 controllerAs 它的类型不一致。 github 中有一个错误报告 (github.com/angular/angular.js/issues/7635)。它已关闭,但我认为它没有修复。
  • 正如我在我身边添加的那样,虽然我没有从孩子到父母的数据绑定工作,但只是从父母到孩子似乎没有工作
【解决方案2】:

我在 $compile 服务中找到了一个属性来解决这个问题。将属性 bindToController:true 添加到指令中会获取作用域属性中定义的所有变量并将它们附加到控制器而不是作用域本身,这意味着 2 方式数据绑定是到控制器上的变量而不是作用域上的变量.所以最终结果有这些变化

在你的指令定义中

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

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

这是updated jsfiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多