There is an accordion work menu:

<ul> <li ng-repeat="li in list"><a ng-click="li.clicked=!li.clicked;" ng-href="{{li.link === '#' ? '':li.link}}"><i class="fa" ng-class="li.icon"></i> {{li.name}}<i class="pull-right fa fa-angle-right" ng-show="li.submenu.length"></i></a> <ul class="childrenul" ng-class="{'show':li.clicked && li.submenu.length}"> <li ng-repeat="subitem in li.submenu">{{subitem}}</li> </ul> </li> </ul> 

But I would like to open only one tab, and now everything is open. How can this be implemented in ng-repeat?

  • add the list example to the question , and generally the controller. Ideally, an example that can be run: either here in the snippet, or on Plunkr - Grundy

1 answer 1

In the controller:

 $scope.openedIndex = 1; $scope.openRoot = function(index) { $scope.openedIndex = index; } 

In the view.

 <ul> <li ng-repeat="li in list"> <a ng-click="openRoot($index)" ng-href="{{li.link === '#' ? '':li.link}}"> <i class="fa" ng-class="li.icon"></i> {{li.name}} <i class="pull-right fa fa-angle-right" ng-show="li.submenu.length"></i> </a> <ul class="childrenul" ng-class="{'show': openedIndex == $index && li.submenu.length}" ng-attr-id="{{li.id}}"> <li ng-repeat="subitem in li.submenu">{{subitem}}</li> </ul> </li> </ul> 

Description:
You save the index of the selected item in the menu. Let it be the element with the index 1. ($ index is the index in ng-repeat on which the loop is now located). You hang the event of the openRoot click openRoot($index) - i.e. You transfer to the controller a new index of a new selected item. The submenu looks openedIndex is equal to the index of the submenu, if so, it opens it.

  • function is not particularly needed - Grundy
  • I always carry such functionality in the function, I do not need the view to edit the state, no thanks) The view should only tell you that the state should be changed, and the controller should process the new state - Vasily Barbashev
  • there is no point in making a function for a single line that does not affect anything inside the controller. - Grundy
  • Yes, I'm not talking about it .. you do not understand me at all. I'm just saying that this is not right, and it is not necessary to vaccinate people who are just learning to write, to the bad. Better not show "it works that way", but "it works that way". - Vasily Barbashev
  • That's right - a purely subjective concept. - Grundy