如何使用angularjs一次只激活一个菜单项

时间:2016-02-12 04:15:14

标签: jquery angularjs

我尝试只将一个菜单项设为有效。但是当我点击特定菜单项时,我将所有菜单项都激活。

我想删除之前的活动菜单项,并将当前点击的菜单项设为有效。任何人都可以帮我解决这个问题。

我的js:

angular.module('myapp')
    .controller('myCtrl', function ($scope) {

       $scope.isActive = true;
        $scope.highlight = function () {


            if (!$(event.target).hasClass("active")) {
                $(event.target).addClass("active");
                $(event.target).children().addClass("glyphicon-triangle-top");
            } else {
                $(event.target).removeClass('active');
                $(event.target).children().removeClass("glyphicon-triangle-top");
            }
        }


    });

我的HTML:

 <div class="collapse navbar-collapse" id="js-navbar-collapse">
                    <ul class="nav navbar-nav">
                        <li id="li-home">
                            <a ng-click="highlight()" class="active" href="#/">Home
                    <span class="glyphicon glyphicon-triangle-top active-elem"></span></a>
                        </li>
                        <li id="li-about"><a ng-click="highlight()" ng-href="#/about">About
                    <span class="glyphicon active-elem"></span>
                  </a></li>
                        <li id="li-contact"><a ng-click="highlight()" ng-href="#/">Contact
                    <span class="glyphicon active-elem"></span>
                  </a></li>
                    </ul>
                </div>

2 个答案:

答案 0 :(得分:0)

所以...我会给你另一种做法,因为你的代码似乎是艰难的做事方式。关键区别在于我使用 ngClass 来动态设置活动标签的类:

angular.module('myapp')
.controller('myCtrl', function ($scope) {

   $scope.isActive = 'home';
   $scope.highlight = function(tab) {
     $scope.isActive = tab;
   }
});

HTML:

<div class="collapse navbar-collapse" id="js-navbar-collapse">
  <ul class="nav navbar-nav">
    <li id="li-home" ng-class="{activeTab: isActive === 'home'">
      <a ng-click="highlight('active')"  href="#/">
        Home
        <span ng-show="isActive === 'home'" class="glyphicon active-elem</span>
      </a>
    </li>
    <li id="li-about" ng-class="{activeTab: isActive === 'about'">
      <a ng-click="highlight('about)" ng-href="#/about">
        About
        <span ng-show="isActive === 'about'" class="glyphicon active-elem"></span>
      </a>
    </li>
    <li id="li-contact" ng-class="{activeTab: isActive === 'contact'">
      <a ng-click="highlight('contact)" ng-href="#/">
        Contact
        <span ng-show="isActive === 'contact'" class="glyphicon active-elem"></span>
      </a>
    </li>
  </ul>
</div>

的CSS:

.activeTab {
  background-color: red;
}

答案 1 :(得分:0)

您可以创建一个简单的指令,用于切换元素上的活动类。

请参阅..

Toggle class with ng-click on several elements