【问题标题】:How to access to the controller scope from a directive inside ng-repeat?如何从 ng-repeat 中的指令访问控制器范围?
【发布时间】:2013-11-09 23:52:53
【问题描述】:

我是 AngularJS 的新用户,当我必须从 ng-repeat 中的指令访问控制器中的变量时,我遇到了困难。我认为它必须与范围有关。

这是我的小提琴:http://jsfiddle.net/Zzb58/1/

“MyCtrl”范围有两个属性:“items”,一个数组,和“thing”,一个字符串。

function MyCtrl($scope) {
    $scope.items = [{id: 'item1'}, {id: 'item2'}];    
    $scope.thing = "thing";
}

所以,如果我创建一个指令并希望它读取数组的内容,那么这个指令可以完美运行:

<div my-directive ng-repeat="item in items" item='item'></div>
app.directive('myDirective', function () {
    return {
        restrict: 'AE',
        scope: {
            item: '=item',
        },
        template: '<div>{{ item.id }}</div>'
    }
});

HTML 已正确刷新。

但如果我尝试从指令中访问“事物”变量,它总是被读取为“未定义”。

app.directive('myDirective', function () {
    return {
        restrict: 'AE',
        scope: {
            item: '=item',
            thing: '='
        },
        template: '<div>{{ item.id }} - Here is not the {{thing}}</div>'
    }
});

我认为问题必须与在 ng-repeat 中创建的范围子级有关,或者变量可能没有正确绑定。

但是,如果我在模板中使用 $parent.thing,则会读取该变量并对其进行正确评估,但我不知道该 $parent 是 ng-repeat 范围还是“MyCtrl”范围。

1) 我做错了什么?

2) 为什么需要将ng-repeat中读取的“item”元素作为HTML元素的一个属性?我首先认为“items”在父范围内,所以当创建指令的隔离范围时,我只需要执行“items: '='”之类的操作。

【问题讨论】:

  • 如果你使用=,那么你必须像thing="thing"那样传递属性。

标签: javascript html angularjs


【解决方案1】:

通过为它分配一个对象,您可以创建一个隔离范围。如果你设置了scope : true,你可以像在你的例子中那样使用它,否则你必须将它作为一个属性传递,就像你对item所做的那样。

http://jsfiddle.net/Zzb58/2/

有关不同范围模式的说明,您可以阅读此页面上的指令部分: https://github.com/angular/angular.js/wiki/Understanding-Scopes

通常,但尤其是在处理继承的范围值时,我还强烈建议使用具有属性集的对象,而不是简单的字符串变量,因为由于原型继承的工作方式,这可能会导致整个范围的分离.

【讨论】:

  • 有效!我想我开始了解作用域和 JavaScript 原型继承...非常感谢!
猜你喜欢
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多