Home » Angularjs » How to alias object property as variable in ng-repeat

How to alias object property as variable in ng-repeat

Posted by: admin November 29, 2017 Leave a comment

Questions:

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?

Answers:

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

Questions:
Answers:

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";

Leave a Reply

Your email address will not be published. Required fields are marked *