如何从父级以 ng 重复的方式遍历控制器



我想编写一个 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
    }
};
});
我知道

我没有得到很多答案,但它让我意识到我实际上是在倒着想。我在 json 数据中设置了一个"已检查"属性,并将其设置为 ng-checked。至于 setAll 函数,我只是使用 forEach 遍历 JSON,并将每个 .checked 值设置为 = true/false。谢谢大家:)

最新更新