How to set active class on ng-click?

前端 未结 5 684
轮回少年
轮回少年 2020-12-23 17:42

I have this:

相关标签:
5条回答
  • 2020-12-23 18:20

    Ok say you have multiple menu items and you want to toggle the class according to click,

    you can create a array in the controller which represents the menu items as,

    $scope.menuItems = ['Home', 'Contact', 'About', 'Other'];
    

    assign the default selected ,menu item

    $scope.activeMenu = $scope.menuItems[0];
    

    create a function to assign the selected Menu value, this function will assign the $scope.activeMenu a last selected menu item.

     $scope.setActive = function(menuItem) {
        $scope.activeMenu = menuItem
     }
    

    in HTML

    loop through the menuItems array and create the menu.

    in the ng-class check last clicked menu item is equal to item in the repeat.

    if click on the menu then call setActive() function in the controller and pass the menu item name as an argument.

    <div class="account-item" ng-repeat='item in menuItems'>
       <div class="account-heading" ng-class="{active : activeMenu === item}">
          <h4 class="account-title">
            <a href="#/Messages" ng-click="setActive(item)"> {{ item }}</a>
          </h4>
       </div>
    </div>
    

    here is the DEMO

    here is a DEMO without ng-repeat

    0 讨论(0)
  • 2020-12-23 18:25

    This is what you need.

    <div class="account-item" ng-init="active = true">
      <div class="account-heading" ng-class="{'active': active === true}" ng-click="active = !active">
        <h4 class="account-title">
            <a href="#/Messages">7.    @Translate("SYSTEM_MESSAGES")</a>
        </h4>
      </div>
    </div>
    

    No other scripting. +1 if it helps.

    0 讨论(0)
  • 2020-12-23 18:25

    If you are using [ui-router] you not need to write anything just you have add this ui-sref-active="active-menu" property in your tag which you want to active after click/navigate.

    0 讨论(0)
  • 2020-12-23 18:35

    Angular4:

    <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
    
    <a [routerLink]="['calendar']" routerLinkActive="active">
    

    Documentation: https://angular.io/api/router/RouterLinkActive

    0 讨论(0)
  • 2020-12-23 18:38

    For cleaner code try this:

    <div class="account-item" ng-init="active = true">
      <div class="account-heading" ng-class="{'active': active}">
        <h4 class="account-title">
            <a href="#/Messages" ng-click="active = !active">7. @Translate("SYSTEM_MESSAGES")</a>
        </h4>
      </div>
    </div>
    


    You can remove the onclick event SetActiveAccountHeading(this);.

    Here's the JsFiddle link.

    You can view the result in the developer's console.

    Hope it helps.

    0 讨论(0)
提交回复
热议问题