AngularJS – ngRepeat with multiple object types

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="https://stackoverflow.com/questions/14425497/item.src">
       <a ng-use="item.type == 'vehicle'">{{item.link}}</a>
       <span ng-use="item.type == 'animal'">{{item.name}}</span>
    </li>
</ul>

<ul>
    <li ng-repeat="item in items" ng-switch="item.type">
       <img ng-switch-when="user" ng-src="https://stackoverflow.com/questions/14425497/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

Although this doesn’t use ng-switch, it does get round the problem of not having a type field, which @DotNetHaggis pointed out.

<div ng-repeat="field in fields">
    <div ng-if="field.user !== undefined">user info</div>
    <div ng-if="field.vehicle !== undefined">vehicle info</div>
    <div ng-if="field.animal !== undefined">animal info</div>
</div>


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Google Maps JavaScript API RefererNotAllowedMapError

Similar Posts