Thursday, December 11, 2014

ng-repeat working with JSON objects

today i had quite  a fight vs ng-repeat while trying to loop over some json objects
i'll just sum it cause in the end its quite easy. you can try it yourself, I prepared a little jsbon for it:
http://jsbin.com/roranijaba/1/edit?html,output

1 - simple array
this is just for the sake of the example, when your object in an array, ngRepeat looks like this
<div ng-init="friends = ['Jhonny','Jessy','Marky']">
  <ul>
    <li ng-repeat="friend in friends">
      {{friend}}.
    </li>
  </ul>
</div>



2 - array of json objects
this is where you can use the power of parameter with ngRepeat
<div ng-init="friends = [{name:'John', age:25, gender:'boy'},
       {name:'Jessie', age:30, gender:'girl'},
       {name:'Patrick', age:40, gender:'boy'}]">
  <ul>
    <li ng-repeat="friend in friends">
      {{friend.name}} who is {{friend.age}} years old.
    </li>
  </ul>
</div>


3 - json dictionay object
this is when your json obj acutally has  properties, while each represents an array of either simple values or json objects, here is an example of both
<div ng-init="friendsDictionary =
    { boys : [{name:'John', age:25, gender:'boy'},
              {name:'Peter', age:95, gender:'boy'}],
     girls : [{name:'Jessie', age:30, gender:'girl'},
              {name:'Samantha', age:60, gender:'girl'}]}">
  <ul ng-repeat="(gender, friends) in friendsDictionary">
    <li>{{gender}}</li>
    <li ng-repeat="friend in friends">
      {{friend.name}} who is {{friend.age}} years old.
    </li>
  </ul>
</div>


4 - json object of json objects - NO
you just cant do this, sorry. you must change the architecture to a json dictionay at least.

5 - putting ng-repeat in the same element of ng-controller - NO
you just cant do this, sorry. kind of understandable.

live example for all this :
http://jsbin.com/roranijaba/1/edit?html,output

No comments:

Post a Comment