AngularJS使用ng-view在ng-repeat内渲染不同的模板

时间:2014-05-21 07:18:57

标签: angularjs angularjs-ng-repeat angularjs-routing ng-view

我想道歉,我无法提供有关此问题的任何代码段,我是关于 AngularJS 的新手。

<div ng-repeat="item in list" ng-view></div>

使用上面的代码,是否可以呈现依赖于item.type属性的不同模板。我期待这样的结果:

  • item.type ==“image”返回: <div><img src="'IMAGE_URI'"></div>
  • item.type ==“text”返回: <div><p>TEXT</p></div>

截至目前,我已为枚举item.type创建了一个模板html。使用 AngularJS 可以解决这个问题吗?我最近了解到ng-view伴随ng-route

2 个答案:

答案 0 :(得分:3)

我认为你可以做的一种方法是使用'ng-if'有条件地包含html:

 <div ng-repeat="item in list">
      <div ng-if="item.type == 'image'><img src="'IMAGE_URI'"></div>
      <div ng-if="item.type == 'text'><div><p>TEXT</p></div>
 </div>

答案 1 :(得分:2)

您只能有一个ng-view,
看看这个answer

来自documentation的ng-view:

ngView is a directive that complements 
the $route service by including the rendered
template of the current route into the main
layout (index.html) file.

Every time the current route changes,
the included view changes with it according 
to the configuration of the $route service.

Requires the ngRoute module to be installed.

您正在寻找的是ng-include,并结合ng-switch, 看看这个answer如何将两者结合起来。

ng-include创建一个新的子范围,该范围又从控制器继承。 有关该主题的更多信息,请查看此answer

相关问题