"分组"在Angular JS中使用平面JSON进行ng-repeat?

时间:2014-06-02 19:39:57

标签: javascript json angularjs

过去,我使用嵌套的JSON数据进行了“分组”ng-repeat。这次,我遇到了一个Feed,例如:

...{
"name": "Film",
"id": "film",
"unicode": "f008",
"created": 1,
"categories": [
  "Web Application Icons"
]
}, {
"name": "th-large",
"id": "th-large",
"unicode": "f009",
"created": 1,
"categories": [
  "Text Editor Icons"
]
}, {
"name": "th",
"id": "th",
"unicode": "f00a",
"created": 1,
"categories": [
  "Text Editor Icons", "Medical Icons"
]
},...

我正在尝试使用按类别分组的图标创建一个页面,例如

Web Application Icons
    -- ng-repeat of matching icons
Text Editor Icons
    -- ng-repeat of matching icons
Medical Icons
    -- ng-repeat of matching icons

我试过这个开始,之前曾经使用多个级别的数据:

<div class="row" ng-repeat="i in icons">
<h3 class="sh">{{i.categories[0]}}</h3>
   <div class="col-md-4 col-sm-6 col-lg-3" ng-repeat="j in i.children | filter:faIconSearch">
        <p><i class="fa fa-fw fa-{{j.id}}"></i> fa-{{j.id}}</p>
   </div>

但这不适用于此。我错过了什么? (同样,我需要使用数据)。

1 个答案:

答案 0 :(得分:0)

创建一个函数来获取所有类别:

$scope.getCategories = function() {
    var categories = [];

    angular.forEach($scope.icons, function(item) {
      angular.forEach(item.categories, function(category) {
        if (categories.indexOf(category) == -1) {
          categories.push(category);
        }
      })
    });
    return categories;
  }

现在,您可以遍历各个类别,并在该循环中覆盖所有图标,仅过滤具有匹配类别的图标。

<div class="row" ng-repeat="cat in getCategories()">
  <h3>{{cat}}</h3>
  <div ng-repeat="icon in icons | filter:{categories: cat}">
    <span style="margin-left: 20px">{{icon.name}}</span>
  </div>
</div>

Plunker