burakkesepara
burakkesepara

Reputation: 316

Toggle menu with ng-repeat

I have a sidebar with toggle menus of companies. I get the companies data from api and print it out. And each company has same two subtitle "documents" and "add new document".

I use ng-repeat for printing all the companies to sidebar. And i couldn't find any solution to toggle these menus.

Last thing i found is this:

    <li data-ng-click="toggleMenu($event)" ng-repeat="company in companies" >
       <a class="nav-submenu" data-toggle="nav-submenu" href="#">
           <span class="sidebar-mini-hide">{{company.name}}</span>
       </a>

       <ul>
          <li>
            <a data-ui-sref="{{company.id}}" data-ui-sref-active="active">
                <i class="fa fa-file-text-o"></i>Company's Documents
            </a>
          </li>

          <li>
            <a data-ui-sref="{{company.id}}" data-ui-sref-active="active">
               <i class="fa fa-plus"></i>Add New Document
            </a>
          </li>
        </ul>
  </li>

Here is the Js Code:

   $scope.toggleMenu = function($event){

     $($event.currentTarget).toggleClass('open');
     $($event.currentTarget).siblings().removeClass('open');

   };

But this code causes menu to close whenever i click on the "add new document" or "documents" of any company.

Any help would be great for me !

Thanks, Burak

Upvotes: 2

Views: 1934

Answers (1)

Alon Eitan
Alon Eitan

Reputation: 12025

As I wrote in the comment: You should avoid as much as possible uglifying your angular code with jQuery.

I suggested the following as an alternative:

<li ng-class="{open: company.isOpen}" ng-repeat="company in companies" >
   <a ng-click="company.isOpen = !company.isOpen" class="nav-submenu" data-toggle="nav-submenu" href="#">
       <span class="sidebar-mini-hide">{{company.name}}</span>
   </a>

But as you correctly say, it won't close to menu if you're clicking on another company menu.

So here is a similar, but different approach:

<li ng-class="{open: currentOpen.companyId == company.id}" ng-repeat="company in companies" >
   <a ng-click="currentOpen.companyId = currentOpen.companyId == company.id ? null : company.id" class="nav-submenu" data-toggle="nav-submenu" href="#">
       <span class="sidebar-mini-hide">{{company.name}}</span>
   </a>

This will store the company id when you click on it in an object: $scope.currentOpen.companyId, and will add the open class if it matched to the same company id inside the ngRepeat loop.

Working example: https://jsfiddle.net/jsv2q4bm/

Upvotes: 2

Related Questions