我编写了以下指令:
var gameOdds = function(){
return {
template: '{{games["@homeTeam"]}} vs {{games["@awayTeam"]}}',
scope: {
games: '@'
}
};
};
<div game-odds games="{{games}}">
这使用以下 JSON 数据(部分 json 如下):
{
@id: "69486",
@homeTeam: "Home Team",
@awayTeam: "Away Team",
otherNormalValues : {
etc: "normal..."
}
}
我知道选择这些以 @ 符号开头的键的方法在直接放入绑定(bind)到 Controller 的 HTML 中时有效。但在我的指令中,我无法以这种["@field"]
方式选择字段。
有人知道怎么做吗?
最佳答案
您可以使用 =
,而不是使用属性对象表示法 @
。
<强> DEMO
JAVASCRIPT
.directive('gameOdds', function() {
return {
template: '{{games.homeTeam}} vs {{games.awayTeam}}',
scope: {
games: '='
}
}
});
HTML
<div game-odds games="games"></div>
更新:抱歉回复晚了,正如已接受的答案所提到的,如果 key 以特殊字符开头,您可以使用 []
表示法访问它们:
.directive('gameOdds', function() {
return {
template: '{{games['@homeTeam']}} vs {{games['@awayTeam']}}',
scope: {
games: '='
}
}
});
关于javascript - AngularJS 如何从指令访问 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25806876/