add/remove class of multiple li in angularjs

邮差的信 提交于 2019-12-02 23:09:51

问题


I have list as below...

<ul id="menu">
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

Now, when a particular li is clicked, I want the active class to be added to the same and remove active class from the rest of the li elements. Also, when the same li is clicked again I want to remove active class.

How, can i do this using ng-click and ng-class?


回答1:


Check the below example:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.setMaster = function(section) {
    $scope.selected = section;
  }

  $scope.isSelected = function(section) {
    return $scope.selected === section;
  }
}]);
.active {
    background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
    <ul>
      <li ng-repeat="i in ['One', 'Two', 'Three']" ng-class="{active : isSelected(i)}">
        <a ng-click="setMaster(i)">{{i}}</a>
      </li>
    </ul>
    <hr> {{selected}}
</div>


来源:https://stackoverflow.com/questions/41699215/add-remove-class-of-multiple-li-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!