Kaya February 2016

How can you iterate through controllers in an ng-repeat from the parent?

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) {
               

Answers


Kaya February 2016

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 :)

Post Status

Asked in February 2016
Viewed 2,068 times
Voted 9
Answered 1 times

Search




Leave an answer