我有两个数组。如果ctrl.type == 'group'
我想要ng-repeat
<div ng-repeat="category in ctrl.categories">
...
<div ng-repeat="item in category.group_items">...</div>
</div>
否则,它应该是
<div ng-repeat="category in ctrl.categories">
...
<div ng-repeat="item in category.data.other_items">...</div>
</div>
写这个的最好方法是什么?我不想重写...
,因为它是相同的代码。
答案 0 :(得分:2)
创建一个返回控制器中数组的函数。
ctrl.getArray = () => {
if(ctrl.type === 'something') {
return ctrl.data.group_items;
}
return ctrl.data.other_items;
}
在视图中:
<div ng-repeat="item in ctrl.getArray()">...</div>
答案 1 :(得分:1)
也可以使用ng-switch完成。下面是我的控制器代码,其中我已经定义了两个数组,并且还定义了将在其上显示数据的类型。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.type = 'something';
$scope.categories=[{ID:'1',Name:'Test 1'},{ID:'2',Name:'Test 2'},{ID:'3',Name:'Test 3'}];
$scope.group_items=[{ID:'1',Name:'Group 1'},{ID:'2',Name:'Group 2'},{ID:'3',Name:'Group 3'}];
});
下面是html绑定。
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-switch="type">
<div ng-switch-when="group">
<div ng-repeat="item in categories">
<p>{{item.Name}}</p>
</div>
</div>
<div ng-switch-when="something">
<div ng-repeat="item in group_items">
<p>{{item.Name}}</p>
</div>
</div>
</div>
</div>