user869375 user869375 - 25 days ago 6
AngularJS Question

toggle ngClass in nested ngRepeat

I have a nested ngRepeat and I have to apply some css class on each item in nested structure when I click on some div. This is what I have till now (simplified version of code) -

View

<div ng-repeat="item in vm.userItems">
<div ng-repeat="child in item.children" ng-class="vm.childSelected($parent.$index,$index)" ng-click="vm.toggleChild($parent.$index,$index)">
<div class="panel-body">
{{:: child.name}}
</div>
</div>
</div>


Controller

vm.isChildSelected = [];

vm.toggleChild = function (parentId, id) {

vm.isChildSelected[parentId, id] = (vm.isChildSelected[parentId, id] == "" || vm.isChildSelected[parentId, id] == undefined) ? "goal-added" : "";

//classes change for every nth element in each column - NOT WHAT I WANT
console.info(vm.isChildSelected[0, 0] + "," + vm.isChildSelected[1, 0] + "," + vm.isChildSelected[2, 0] + "," + vm.isChildSelected[3, 0] + "," + vm.isChildSelected[4, 0]);

//Setting of class/passing argument is just fine
console.info(parentId + "," + id + ":" + vm.isChildSelected[parentId, id]); //works just fine
};

vm.childSelected = function (parentId, id) {
return vm.isChildSelected[parentId, id];
};


The problem I have is that on console, I see everything logged correctly when I set the class on a div on clicking, but when ng-class expression is evaluated, classes change for every nth element in each column.

I think the problem lies with how I have declared the array. Any pointers?

Answer

What about simple solution:

<div ng-repeat="item in vm.userItems">
    <div ng-repeat="child in item.children" ng-class="{'goal-added':flag}" ng-click="flag=!flag">
        <div class="panel-body">
            {{:: child.name}}
        </div>
    </div>
</div>