在angularjs中添加/删除多个li的类

时间:2017-01-17 14:05:50

标签: angularjs ng-class

我的列表如下......

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

现在,当点击特定的li时,我希望将active类添加到同一个类中,并从active元素的其余部分中删除li类。此外,再次点击相同的li时,我想删除active类。

我是如何使用ng-clickng-class

执行此操作的

1 个答案:

答案 0 :(得分:1)

检查以下示例:

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>