我有一个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
列的嵌套列表,
如何使用angularjs完成?
答案 0 :(得分:2)
利用内部ng-repeat
和filter
/ 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