angular.js ng-repeat division

时间:2015-08-15 16:02:41

标签: javascript angularjs

我有一系列具有这种结构的类别:

{
name: 'something',
main_category: 'A'
}

所以每个类别都有它的主要类别。我想在html中显示所有类别,如:

<h1>A</h1>
<ul>
<li>list of categories that has main category A</li>
</ul>
<h1>B</h1>
<ul>
<li>list of categories that has main category B</li>
</ul>

我应该如何实现它?我找到的唯一方法是做这样的事情:

<h1>A</h1>
<ul>
<li ng-repeat="category in categories" ng-if="category.main_category == 'A'">..</li>
</ul>
<h1>B</h1>
<ul>
<li ng-repeat="category in categories" ng-if="category.main_category == 'B'">..</li>
</ul>

它有效,但我认为这不是一个好主意。

2 个答案:

答案 0 :(得分:5)

您应该使用https://github.com/a8m/angular-filter提供的groupBy过滤器,并执行类似这样的操作

&#13;
&#13;
var myApp = angular.module('mcApp', ['angular.filter']);

myApp.controller('mcController', ['$scope', function ($scope) {
        console.log('asadsds');
        $scope.myArray = [
          {
            name: 'something 1',
            main_category: 'B'
          },
          {
            name: 'something 2',
            main_category: 'A'
          },
          {
            name: 'something 3',
            main_category: 'A'
          },
          {
            name: 'something 4',
            main_category: 'B'
          },
          {
            name: 'something 5',
            main_category: 'B'
          }
          ];
  
}]);
&#13;
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example7-production</title>
  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.5/angular-filter.js"></script>
  <script src="app.js"></script>
  

  
</head>
<body ng-app="mcApp" ng-controller="mcController">
<p>{{name}}</p>

<div ng-repeat="object in myArray | orderBy: 'main_category'| groupBy:'main_category' |toArray: true" >
  <h1>{{object.$key}}</h1>
  <ul>
    <li ng-repeat="value in object">
      {{value.name}}
    </li>
  </ul>
</div>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

See this answer了解如何使用Angular的filter: { prop: 'value' }语法在此用例中实现与ng-if相同的功能:

<h1>A</h1>
<ul>
    <li ng-repeat="category in categories | filter: {main_category: 'A'}"></li>
</ul>

<h1>B</h1>
<ul>
    <li ng-repeat="category in categories | filter: {main_category: 'B'}"></li>
</ul>