如何渲染异构对象的集合



给定JSON响应:

[
  { type: 'A', name: 'Clem', created_at: '...', ... },
  { type: 'B', url: 'http://go.gl/H65Fs90x', created_at: '...', ... },
  { type: 'C', city: 'Berlin', created_at: '...', ... }
]

散列已被简化;认为它比这个例子更复杂。

如何使用ngRepeat渲染此异构对象集合?

     <li ng-repeat="object in objects">
        // if object is of type A then render fields of object
        // if object is of type B then render fields of object
     </li>

有更好的方法吗?更"棱角分明"的东西?

如果您有两个以上的条件,或者如果结构更复杂,那么类似这样的东西(代码未测试)

<li ng-repeat="object in objects">
   <span ng-if="object.type == 'A'">{{object.name}}</span>
   <span ng-if="object.type == 'B'">{{object.url}}</span>
   <span ng-if="object.type == 'C'">{{object.city}}</span>
</li>

实现这一点的一种方法是让绑定的项负责知道它们将如何呈现。这可以简单到为每个项目提供一个templateUrl。以下是该技术的一个应用示例:http://jsbin.com/EhAnIMaJ/2/edit?html,js,输出

最新更新