19

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?

Erik Kallevig
  • 513
  • 1
  • 6
  • 16
  • 1
    I guess not, however you could use ng-init `
    {{ name.first }}
    `
    – PSL Sep 19 '14 at 16:07
  • 1
    This question turned up miraculously in a not-very-well-worded Google search. It was exactly what I needed. – Nate Jan 11 '15 at 15:20

2 Answers2

21

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

tommybananas
  • 5,718
  • 1
  • 28
  • 48
1

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";
Antern
  • 43
  • 4