如何根据数组中不同类别的类别使用ng-repeat

时间:2015-05-16 10:38:16

标签: javascript html angularjs

我有像这样的样本数据 让我们专注于描述键 你可以在这个数组中看到包含3个对象,但描述有两种类型(description1和description2) 我需要根据此描述键生成div 在这种情况下,我需要两个div的description1和description2 我怎么能这样做

var apps = [
{
  name: 'Azurite',
  description: "description1",
  shine: 8,
  price: 110.50,
  rarity: 7,
  color: '#CCC',
  faces: 14,
  images: [
    "img/01.png",
    "img/02.png",
    "img/03.png"

  ],
  reviews: [{
    stars: 5,
    body: "I love this gem!",
    author: "joe@example.org",
    createdOn: 1397490980837
  }, {
    stars: 1,
    body: "This gem sucks.",
    author: "tim@example.org",
    createdOn: 1397490980837
  }]
},
{
  name: 'Bloodstone',
  description: "description2",
  shine: 9,
  price: 22.90,
  rarity: 6,
  color: '#EEE',
  faces: 12,
  images: [
    "img/04.png",
    "img/05.png",
    "img/06.png"
  ],
  reviews: [{
    stars: 3,
    body: "I think this gem was just OK, could honestly use more shine, IMO.",
    author: "JimmyDean@example.org",
    createdOn: 1397490980837
  }, {
    stars: 4,
    body: "Any gem with 12 faces is for me!",
    author: "gemsRock@example.org",
    createdOn: 1397490980837
  }]
},{
  name: 'sample ',
  description: "description1",
  shine: 9,
  price: 22.90,
  rarity: 6,
  color: '#EEE',
  faces: 12,
  images: [
     "img/07.png",
    "img/08.png",
    "img/09.png"
  ],
  reviews: [{
    stars: 3,
    body: "I think this gem was just OK, could honestly use more shine, IMO.",
    author: "JimmyDean@example.org",
    createdOn: 1397490980837
  }, {
    stars: 4,
    body: "Any gem with 12 faces is for me!",
    author: "gemsRock@example.org",
    createdOn: 1397490980837
  }]
}]

2 个答案:

答案 0 :(得分:2)

您需要类似groupBy过滤器,https://github.com/a8m/angular-filter实现您可以使用的过滤器。只需将此模块添加到您的应用程序依赖项(angular.module('yourAppName', ['angular.filter'])并在ng-repeat表达式上使用它:

<div ng-repeat="(description, apps) in apps | groupBy : 'description'"></div>

Plunker:http://plnkr.co/edit/5uKHrSkKO5XBVjKraiYC?p=preview

答案 1 :(得分:0)

您也可以在不使用任何额外插件的情况下执行此操作使用forEach函数为控制器中主阵列的每个描述创建不同的数组,然后通过HTML中的ng-repeat循环。< / p>

这是工作的plunker

http://embed.plnkr.co/FXUJGnzkz1K9hL1t4uI1/preview

希望这也有帮助