Search code examples
angularjsangularjs-scopeangularjs-ng-clickangularjs-ng-class

applying class using ng-class for nested items in Angularjs


I am displaying the menu items in the below format. The data contains list of items and for each item there is a subitem. I need to apply the selected class for the subitem selected and all other subitems for all the items should be deselected. How to do this inside the controller. I tried by adding the ng-click event inside the html and toggling the class inside the controller but it is not applying for all the other subitems inside other items. Both html and controller code is shown below for more details.

<ol ng-model="data">
  <li ng-repeat="item in data" collapsed="true">
    <div ng-click="toggle(this)">
      <a class="btn btn-success btn-xs" ng-if="item.children && item.children.length > 0">{{item.name}}</a>
    </div>
      <ol ng-model="item.children" ng-class="{hidden: collapsed}">
        <li ng-repeat="subItem in item.children" ng-model="subItem.name"  collapsed="true" ng-click="handleClick(subItem)">
          <div ng-class="{'selected-li': subItem.value, 'deselected-li': false}">
                  {{subItem.name}}
          </div>
        </li>
      </ol>
    </li>
  </ol>

Inside my controller I am having the code as below:

$scope.toggle = function (scope) {
    scope.toggle();
};

$scope.handleClick=function(subitem){
  subitem.value = subitem.value ?  !subitem.value: true; 
}

The data object used inside the UI contains the children also. Please let me know where I am going wrong.


Solution

  • HTML

    <li ng-repeat="subItem in item.children" ng-model="subItem.name"  collapsed="true" ng-click="handleClick($index, item.children)">
          <div ng-class="{'selected-li': subItem.value, 'deselected-li': false}">
                  {{subItem.name}}
          </div>
    </li>
    

    JS

    $scope.handleClick = function(index, subItems) {
        for(var i = 0; i < subItems.length; i++) {
            if(i == index) {
                subItems[i].value = true;
            } else {
                subItems[i].value = false;
            }
        }
    }
    

    What I'm doing here is, the index of the sub item and the entire item.children array are sent to the ng-click handler method and then in a for loop I am updating the value of all the sub items in that list.