【发布时间】: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