I want to write a for loop that goes through all of the child controllers and runs a function in them. At the moment the code is only running the function in one instance of the child controller. How do I iterate through all instances of the controller, which are generated through ng-repeat?
Basically, on the click of the button the function in childController should be run 4 times, one for each controller generated on each 'set' in '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>
Angular controllers:
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
}
};
});
I know I didn't get many answers to this but it made me realize that I was in fact, thinking about it all backwards. I set up a "checked" property in my json data and just set this for ng-checked. As for the setAll function, i simply iterated through the JSON with a forEach and set each .checked value to = true/false. Thanks everyone :)