AngularJS - ngRepeat with multiple object types

孤者浪人 提交于 2019-12-18 10:35:30

问题


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>

回答1:


<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




回答2:


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>


来源:https://stackoverflow.com/questions/14425497/angularjs-ngrepeat-with-multiple-object-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!