我正在尝试在 ng-repeat 项目上使用指令,每个项目都有一个独立的范围,但它不起作用。我遍历每个项目并使用 inboxuser-select 指令将其着色为红色。但是,当我启用该指令时,它不会显示我的任何范围值。这里的问题是什么?谢谢
html文件
<li class="inbox-chatter" data-ng-
repeat="inboxuser in inboxusers">
<p inboxuser-select selected={{inboxuser}}">{{inboxuser}}</p>
</li>
指令.js
.directive('inboxuserSelect', function() {
return {
restrict: 'A',
scope: {
selected: "@"
},
link: function(scope, element, attrs) {
scope.selected.css('color','red');
}
}
});
最佳答案
问题在于,一旦您在指令上设置了隔离范围,那么整个 DOM 元素都具有该隔离范围。所以 inboxuser
来自你的 ng-repeat
发生数据绑定(bind)时不再在范围内(它在父范围内)。
一个选项是设置 scope
为 true 而不是使用隔离作用域,因此您将从父作用域继承所有内容。
或者您可以坚持使用隔离范围,但传递 inboxuser
进入指令并使用模板显示它。由于您已经通过了 inboxuser
通过 selected
进入指令范围将它添加到您的指令中会很容易:
template: '{{selected}}',
另外,顺便说一下,您的 <p>
上缺少引号.所以这可能更适合您(请注意,我还从 {{inboxuser}}
中删除了 <p>
,假设您将使用模板来显示它):
<p inboxuser-select selected="{{inboxuser}}"></p>
关于javascript - Angularjs 使用 ng-repeat 隔离范围指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19851114/