mercredi 27 janvier 2016

How can you iterate through ng-models within an ng-repeat in an angular controller?

I am pretty new to web dev and trying out angular so there may be many mistakes.. Basically I have a ng-repeat within an ng-repeat and I need to set a model variable within the child repeat onclick of a checkbox in parent repeat. I don't know how to access the models in the child from the parent. I have tried by giving an [$index] but it does not work.

Here is my HTML. I have a parent checkbox which should change the clicked boolean variable of child checkboxes onclick.

<li ng-repeat="set in wordlistSets" ng-controller="setController">

<div class="parentSelector">
<span class="selectorLeft">
    <p> blah </p>
</span>

<span class="selectorRight">
    <input type="checkbox" name="sets" ng-click="selectAll()">
</span>
</div>

<div  ng-repeat="wordlist in set.content"  ng-click="checked[parent.$index][$index] = !checked[parent.$index][$index]">
<span class="selectorLeft">
    <p>more blah</p><br>
    <p>extra blah</p>
</span>

<span class="selectorRight">
    <input type="checkbox" name="wordLists" ng-click="checked[parent.$index][$index] = !checked[parent.$index][$index]" ng-model="checked[parent.$index][$index]">

</span>
</div>

The "SelectAll()" function should iterate through wordlists and toggle the checked variable accordingly. I cant use angulars ng-checked because I need it to toggle and not have the same state as the parent checkbox allways since it can also be set by clciking on the div itself.

Here is the controller.

myApp.controller("setController", function MyController($scope) {
$scope.parentChecked = false;

$scope.selectAll = function() {
    for (var i = 0; i < $scope.set.content; i++) {
        if ($scope.parentChecked) {
            $scope.checked[$scope.index][i] = true;
        } else {
            $scope.checked[$scope.index][i] = false;
        }
    }
}

Here is a picture for reference. Clicking on either the pink selector or the black parent-selector should tick the checkbox. Picture of page setup

Thanks in advance for any help! :D




Aucun commentaire:

Enregistrer un commentaire