我想编写一个遍历所有子控制器并在其中运行函数的 for 循环。目前,代码仅在子控制器的一个实例中运行该函数。如何遍历通过 ng-repeat 生成的控制器的所有实例?
基本上,单击按钮时,childController 中的函数应该运行 4 次,每个控制器在“wordlistSets”中的每个“集合”上生成一次。
HTML:
<button ng-click="setAll(true)">Select All</button><button ng-click="setAll(false)">DeselectAll</button>
<ul>
<li ng-repeat="set in wordlistSets" ng-controller="setController">
<div class="parentSelector">
<input type="checkbox" ng-click="selectAllChildren(set.content)" ng-checked="parentChecked">
</div>
<div ng-repeat="wordlist in set.content" ng-click="toggleCheckbox(wordlist)">
<input type="checkbox" ng-checked="checkedWordlists.indexOf(wordlist)> -1">
</div>
</li>
</ul>
角度控制器:
myApp.controller("parentController", function ($scope) {
$scope.setAll = function(value) {
var index;
for (index in $scope.wordlistSets) {
$scope.setAll.selectAllChildren($scope.wordlistSets[index].content, value);
}
};
});
myApp.controller("childController", function ($scope) {
$scope.parentChecked = false;
$scope.checkedWordlists = [];
$scope.selectAllChildren = function(wordlists) {
if ($scope.parentChecked == false) {
$scope.parentChecked = true;
} else {
$scope.parentChecked = false;
}
var index;
for (index in wordlists) {
$scope.setChild(wordlists[index], $scope.parentChecked);
}
};
$scope.setAll.selectAllChildrenValue = function(wordlists, value) {
if (value == false && $scope.parentChecked == true) {
$scope.parentChecked = false;
} else if (value == true && $scope.parentChecked == false) {
$scope.parentChecked = true;
}
var index;
for (index in wordlists) {
$scope.setChild(wordlists[index], $scope.parentChecked);
}
};
$scope.toggleCheckbox = function(wordlist) {
var index = $scope.checkedWordlists.indexOf(wordlist);
if (index > -1) {//is in array
$scope.checkedWordlists.splice(index, 1);//remove from array
} else {
$scope.checkedWordlists.push(wordlist);//add to array
}
};
$scope.setChild = function(wordlist, parentChecked) {
var index = $scope.checkedWordlists.indexOf(wordlist);
if (parentChecked && index <= -1) {//is not in array
$scope.checkedWordlists.push(wordlist);//add to array
} else if (!parentChecked && index > -1) {//is in array
$scope.checkedWordlists.splice(index, 1);//remove from array
}
};
});