我想编写一个遍历所有子控制器的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
}
};
});
答案 0 :(得分:0)
我知道我没有得到很多答案,但它让我意识到我实际上是在考虑这一切。我设置了一个&#34;检查&#34;我的json数据中的属性,只需将其设置为ng-checked。至于setAll函数,我只是用forEach迭代JSON并将每个.checked值设置为= true / false。谢谢大家:)