结合问题,当在ngRepeat指令 [英] binding issue when a directive in a ngRepeat

查看:124
本文介绍了结合问题,当在ngRepeat指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是它的样子,这里是 Plunker

so this is how it looks like, and here is the Plunker

parent scope 
   ng-repeat
       directive

在指令中有一个属性是双向的结合与亲本范围的可变

in the directive there is an attribute is bi-directional binding with a variable in parent scope.

但我想这是行不通的。(但是我可以理解为什么它不工作)

But this doesn't work as I wanted.(But I can understand why it doesn't work)

原因是ngRepeat将创建它自己的范围内,所以一旦变量在指令改变,角在ngRepeat添加变量,但它留在父母不变的变量。

The reason is ngRepeat will create it's own scope, so once the variable is changed in directive, Angular add a variable in ngRepeat, but it leave the variable in parent unchanged.

我可以做这样的事情的范围。$父。$​​ parent.variable改变变量,但它是有点儿不角的想法。

I can do something like scope.$parent.$parent.variable to change the variable, but it is kinda not the idea in Angular.

我应该怎么办?

此外,如果我在项集合改变重复项目,该项目不能更改。

Moreover, if I change the repeated item in the items collection, the item can't be changed.

由于上述同样的原因。

推荐答案

编辑(再次):它看起来像问题是你需要有引用类型的数组中,如对象或数组

EDIT (again): It looks like the issue is you need to have reference types in your array, such as objects or arrays.

Gloopy是在评论分毫不差。双向绑定是行不通的,因为它看起来像角是创造第二范围配对之间的原语类型(字符串,数字等)的复印件。所以...当你有两个范围双向绑定原始类型的嵌套它的罚款,因为它使用了一个实例,但是当你窝在多台深,它会创建原始的副本,你不再更新相同的实例。

Gloopy was exactly right in the comments. The bi-directional binding wasn't working because it seems like Angular was creating copies of your primitives types (strings, numbers, etc) between the second scope pairing. So... when you have a nesting of bi-directionally bound primitive types between two scopes it's fine because it uses one instance, but when you nest it more than one deep, it creates a copy of the primitive and you're no longer updating the same instance.

这里有一个新的演示

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    { text: 'apples' },
    { text: 'bananas' },
    { text: 'oranges' }
  ];
  $scope.addItem = function(){
    $scope.items.push({ text: 'test' });
  };
});

app.directive('test', function(){
  return {
    restrict: 'E',
    scope: {
      foo: '=foo'
    },
    template: '<div>{{foo}} <a ng-click="bar()">bar</a></div>',
    controller: function($scope){ 
      $scope.bar = function() {
        $scope.foo += '!';
      };
    }    
  };
});

这篇关于结合问题,当在ngRepeat指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆