gpt4 book ai didi

angularjs - 在 angularjs 指令范围内公开对象,无法访问属性

转载 作者:行者123 更新时间:2023-12-03 14:49:08 27 4
gpt4 key购买 nike

所以,我有以下相对简单的 Angularjs 指令

app.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
site: '@',
index: '@'
},
template: '<div>{{site}}</div>',
replace: true,

}
});

这是我在 HTML 中调用指令的地方
<div id="eventGraphic" class="span12">
<my-directive ng-repeat="site in IEvent.sites" site="{{site}}" index="{{$index}}"></my-directive>
</div>

其中,鉴于每个 site是一个对象,产生这个输出(从浏览器复制)
{"name":"Hurlburt","_id":"5148bb6b79353be406000005","enclaves":[]}
{"name":"Walker Center","_id":"5148cca5436905781a000005","enclaves":[]}
{"name":"test1","_id":"5148ce94436905781a000006","enclaves":[]}
{"name":"JDIF","_id":"5148cf37436905781a000007","enclaves":[]}

但是,如果我将指令中的模板更改为
 template: '<div>{{site.name}}</div>',

它不会产生任何输出。这似乎是一个相当简单的用例,有什么想法我可能做错了吗?所需的输出将只是 name每个对象中的字段。

最佳答案

您需要使用 '='映射对象。 '@'意味着您只是将字符串值传递给新范围。

app.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
site: '=', //two-way binding
index: '@' //just passing an attribute as a string.
},
template: '<div>{{site}}</div>',
replace: true,

}
});

然后在您的标记中,不要在属性中使用绑定(bind),只需传递表达式:

<div id="eventGraphic" class="span12">
<!-- below, site="site" is passing the expression (site) to
the two way binding for your directive's scope,
whereas index="{{$index}}" is actually evaluating the expression
($index) and passing it as a string to the index attribute,
which is being put directly into the directive's scope as a string -->
<my-directive ng-repeat="site in IEvent.sites"
site="site"
index="{{$index}}"></my-directive>
</div>

关于angularjs - 在 angularjs 指令范围内公开对象,无法访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15532174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com