基于angularjs中的type列的嵌套列表

时间:2016-07-26 11:56:04

标签: javascript arrays angularjs json list

我有一个angularjs sample here,其中包含一个示例数组

 $scope.myarr = [
{id: 1, name: 'foo',type: 1},
{id: 2,name: 'bar',type: 1},
{id: 3,name: 'quad',type: 2},
{id: 4,name: 'cab',type: 2},
{id: 5,name: 'baz',type: 2},
{id: 6,name: 'cad',type: 3}
];

我自己尝试使用ng-repeat创建一个列表,它可以作为

完成
<ul ng-repeat="x in myarr">
<li>{{x.id}}. {{x.name}} - Type {{x.type}}</li>
</ul>

但实际上需要的是基于x.type列的嵌套列表,

      
  1. 类型1     
            
    • 1。 FOO
    •       
    • 2。杆
    •     
      
  2.   
  3. 类型2     
            
    • 3。四
    •       
    • 4。驾驶室
    •       
    • 5。巴兹
    •     
      
  4.   
  5. 类型3     
            
    • 6。 CAD
    •     
      
  6. 如何使用angularjs完成?

1 个答案:

答案 0 :(得分:2)

利用内部ng-repeatfilter / unique

默认情况下,AngularJS不包含唯一过滤器。您可以使用角度过滤器中的那个。只需加入JavaScript

即可
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>

并在您的应用中包含相关内容:

var app = angular.module('myApp', ['angular.filter']);

有关https://docs.angularjs.org/api/ng/directive/ngRepeat

的更多信息
<div id="app" ng-app="myApp" ng-controller="myCtrl">
  <ul ng-repeat="x in myarr | unique:'type'">
      <li>{{x.id}}. {{x.name}} - Type {{x.type}}</li>
      <ul>
        <li ng-repeat="y in myarr | filter:type=x.id"> 
          {{y.name}}
        </li>   
      </ul>
  </ul>
</div>

angular.module('myApp', []).controller('myCtrl', function($scope) {
 $scope.myarr = [
    {id: 1, name: 'foo',type: 1},
    {id: 2,name: 'bar',type: 1},
    {id: 3,name: 'quad',type: 2},
    {id: 4,name: 'cab',type: 2},
    {id: 5,name: 'baz',type: 2},
    {id: 6,name: 'cad',type: 3}
  ];
});

将给出结果:

Type 1
    1. foo
    2. bar
Type 2
    3. quad
    4. cab
    5. baz
Type 3
    6. cad

查看更新的Fiddle