AngularJS - 具有多种对象类型的 ngRepeat [英] AngularJS - ngRepeat with multiple object types

查看:26
本文介绍了AngularJS - 具有多种对象类型的 ngRepeat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个物品清单.一个项目可以是很多东西,假设列表是这样的:

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]

现在我想使用 ngRepeat 指令渲染列表,该指令将根据对象的类型(多态渲染)使用模板.可以这样做吗?

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?

可能类似于(ng-use 是一个假设指令):

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>

推荐答案

<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 参考:
http://docs.angularjs.org/api/ng.directive:ngSwitch

这篇关于AngularJS - 具有多种对象类型的 ngRepeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆