javascript AngularJS - 具有多种对象类型的 ngRepeat

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14425497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:37:35  来源:igfitidea点击:

AngularJS - ngRepeat with multiple object types

javascriptdompolymorphismangularjsrendering

提问by Shlomi Schwartz

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?

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

maybe something like (ng-useis an hypotheticallydirective):

也许像(ng-use是一个假设的指令):

<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>

回答by Umur Kontac?

<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

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

回答by deejbee

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

虽然这不使用 ng-switch,但它确实解决了没有类型字段的问题,@DotNetHaggis 指出了这一点。

<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>