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>
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>
But that doesn't seem to be working -- is this possible currently?
You can do this with ng-init
:
<div ng-repeat="person in data" ng-init="name=person.name">{{ name.first }}</div>
https://docs.angularjs.org/api/ng/directive/ngInit
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.
// 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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With