Benny
Benny

Reputation: 4321

How to render a collection of heterogeneous objects

Given the JSON response:

[
  { type: 'A', name: 'Clem', created_at: '...', ... },
  { type: 'B', url: 'http://go.gl/H65Fs90x', created_at: '...', ... },
  { type: 'C', city: 'Berlin', created_at: '...', ... }
]

The hash has been simplified; consider it to be more complex than this example.

How can I render this collection of heterogeneous object with ngRepeat?

     <li ng-repeat="object in objects">
        // if object is of type A then render fields of object
        // if object is of type B then render fields of object
     </li>

Is this there a better approach? Something more "Angular-ish"?

Upvotes: 0

Views: 247

Answers (2)

Jeremy Elbourn
Jeremy Elbourn

Reputation: 2690

One way to accomplish this is to make the items you're binding to be responsible for knowing how they're to be rendered. This can be as simple as giving each item a templateUrl. Here is an example of this technique in action: http://jsbin.com/EhAnIMaJ/2/edit?html,js,output

Upvotes: 2

Raza Ahmed
Raza Ahmed

Reputation: 2751

If you have more than two conditions or if structure is more complex then something like this (code not tested)

<li ng-repeat="object in objects">
   <span ng-if="object.type == 'A'">{{object.name}}</span>
   <span ng-if="object.type == 'B'">{{object.url}}</span>
   <span ng-if="object.type == 'C'">{{object.city}}</span>
</li>

Upvotes: 2

Related Questions