目前,我的范围按以下格式列出。
$scope.test = [
{
group: 'Group1',
groupID:0,
items: [
{id: 0, description: 'Item 1', error: true, groupID:0},
{id: 1, description: 'Item 2', error: true, groupID:0},
{id: 2, description: 'Item 3', error: true, groupID:0},
{id: 3, description: 'Item 4', error: true, groupID:0}
]
},
{
group: 'Group2',
groupID:1,
items: [
{id: 0, description: 'Item 1', error: true, groupID:1},
{id: 1, description: 'Item 2', error: true, groupID:1},
{id: 2, description: 'Item 3', error: true, groupID:1},
{id: 3, description: 'Item 4', error: true, groupID:1}
]
},
{
group: 'Group3',
groupID:2,
items: [
{id: 0, description: 'Item 1', error: true, groupID:2},
{id: 1, description: 'Item 2', error: true, groupID:2},
{id: 2, description: 'Item 3', error: true, groupID:2},
{id: 3, description: 'Item 4', error: true, groupID:2}
]
}
我想要的是循环遍历控制器内每个父对象中的所有项目对象,并获得值' error'等于真,并提醒这个总数。
目前在控制器内部我只能循环遍历阵列中的第一级对象,因此只能访问' group'和' groupID'。
答案 0 :(得分:4)
function myCtrl($scope) {
$scope.test = [{
group: 'Group1',
groupID: 0,
items: [{
id: 0,
description: 'Item 1',
error: true,
groupID: 0
}, {
id: 1,
description: 'Item 2',
error: true,
groupID: 0
}, {
id: 2,
description: 'Item 3',
error: true,
groupID: 0
}, {
id: 3,
description: 'Item 4',
error: true,
groupID: 0
}]
}, {
group: 'Group2',
groupID: 1,
items: [{
id: 0,
description: 'Item 1',
error: true,
groupID: 1
}, {
id: 1,
description: 'Item 2',
error: true,
groupID: 1
}, {
id: 2,
description: 'Item 3',
error: true,
groupID: 1
}, {
id: 3,
description: 'Item 4',
error: true,
groupID: 1
}]
}, {
group: 'Group3',
groupID: 2,
items: [{
id: 0,
description: 'Item 1',
error: true,
groupID: 2
}, {
id: 1,
description: 'Item 2',
error: true,
groupID: 2
}, {
id: 2,
description: 'Item 3',
error: true,
groupID: 2
}, {
id: 3,
description: 'Item 4',
error: false,
groupID: 2
}]
}];
$scope.errors = [];
function innerLoop(obj) {
return function (items) {
for (var i = 0; i < items.length; i++) {
if (items[i].error) {
$scope.errors.push(items[i].error);
}
}
}(obj.items);
}
function loop(obj) {
for (var i = 0; i < obj.length; i++) {
innerLoop(obj[i]);
}
return $scope.errors;
}
loop($scope.test);
alert($scope.errors.length);
}
答案 1 :(得分:0)
您可以在视图中使用嵌套的ng-repeat
参见示例
function myCtrl($scope){
$scope.multi = [1,2,[3,4,5]] ;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="myCtrl">
<div ng-repeat='i in multi'>
<span ng-hide="i.length>1">{{i}}</span>
<div ng-repeat='i2 in i'>
{{i2}}
</div>
</div>
&#13;