javascript 如何在 ng-repeat 中将对象属性别名为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25938059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to alias object property as variable in ng-repeat
提问by Erik Kallevig
I'm repeating over an array of objects and I want my variable in the loop to refer to just one property of each object.
我正在重复一组对象,我希望循环中的变量只引用每个对象的一个属性。
Simplified data example:
简化数据示例:
var data = [
{
'name': {
'first': 'John',
'last': 'Johnson'
}
'age': 45
},
{
'name': {
'first': 'Larry',
'last': 'Wilson'
}
'age': 45
}
]
I could do:
我可以做:
<div ng-repeat="person in data">{{ person.name.first }}</div>
<div ng-repeat="person in data">{{ person.name.first }}</div>
But what I'd prefer to do is to just focus in on the only part of the object I'm using and do something like this:
但我更喜欢做的是只关注我正在使用的对象的唯一部分,然后做这样的事情:
<div ng-repeat="person.name in data as name">{{ name.first }}</div>
<div ng-repeat="person.name in data as name">{{ name.first }}</div>
But that doesn't seem to be working -- is this possible currently?
但这似乎不起作用——目前这可能吗?
回答by tommybananas
You can do this with ng-init
:
你可以这样做ng-init
:
<div ng-repeat="person in data" ng-init="name=person.name">{{ name.first }}</div>
回答by Antern
Beware of using the "ng-init" trick. This will bind the "name" variable to a "person" object instead of making an actual alias for the data[$index].name expression you may want.
当心使用“ng-init”技巧。这会将“name”变量绑定到“person”对象,而不是为您可能需要的 data[$index].name 表达式创建实际别名。
// Init model.
data['fooPerson'] = {name: {first:"foo"}, age:64}
$timeout(function(){
data['fooPerson'] = {name: {first: "bar"}, age:51}
}, 1000);
// Result after ~1 second:
// {{ name.first }} --> still "foo";