Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias object property as variable in ng-repeat

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?

like image 755
Erik Kallevig Avatar asked Sep 19 '14 16:09

Erik Kallevig


2 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

like image 72
tommybananas Avatar answered Nov 16 '22 02:11

tommybananas


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";
like image 24
Antern Avatar answered Nov 16 '22 01:11

Antern