AngularJS - ngRepeat with multiple object types

Shlomi Schwartz picture Shlomi Schwartz · Jan 20, 2013 · Viewed 10.2k times · Source

I have a list of items. An item can be a number of things, let's say the list is something like so :

[userObject , vehicleObject , userObject , animalObject , animalObject]

Now I want to render the list with ngRepeat directive that will use a template according to the type of the object (Polymorphic rendering). can this be done?

maybe something like (ng-use is an hypothetically directive):

<ul>
    <li ng-repeat="item in items">
       <img ng-use="item.type == 'user'" ng-src="item.src">
       <a ng-use="item.type == 'vehicle'">{{item.link}}</a>
       <span ng-use="item.type == 'animal'">{{item.name}}</span>
    </li>
</ul>

Answer

Umur Kontacı picture Umur Kontacı · Jan 20, 2013
<ul>
    <li ng-repeat="item in items" ng-switch="item.type">
       <img ng-switch-when="user" ng-src="item.src">
       <a ng-switch-when="vehicle">{{item.link}}</a>
       <span ng-switch-when="animal">{{item.name}}</span>
    </li>
</ul>

API reference:
http://docs.angularjs.org/api/ng.directive:ngSwitch