AngularJS - 仅为一个元素切换类(ng-class和ng-click)

时间:2015-03-24 20:42:15

标签: javascript angularjs angularjs-ng-click ng-class

我正在尝试一次只将一个类应用于一个元素(see this plunk)。

HTML:

<ul>
  <li ng-repeat="item in listItems">
    <a ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">L</a>
    <a ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">R</a>
    <a ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">J</a>
  </li>
</ul>

JS:

var app = angular.module("testApp", []);

app.controller("MainController", function($scope) {
  $scope.listItems = [{description: 'item1', number: 1}];
});

现在,当我单击此列表中的元素时,类切换将应用于所有元素。

我希望能够单击并取消单击每个字母以单独切换班级更改。我怎么能这样做?

3 个答案:

答案 0 :(得分:4)

困难在于,在您的情况下,所有列表元素都共享相同的范围,因此当您设置isActive时,无法区分哪一个实际上应该是活动的。

对我来说,简单的解决方案是隔离每个项目的范围。也许这不是最好的解决方案,但在非常小的指令的帮助下非常简单:

    <ul>
        <li ng-repeat="item in listItems">
            <a isolate ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">L</a>
            <a isolate ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">R</a>
            <a isolate ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">J</a>
        </li>
    </ul>

其中isolate指令定义为:

app.directive('isolate', function() {
    return {scope: true};
});

答案 1 :(得分:1)

你需要为ng-class使用三个变量,使用一个将反映到任何地方

<a ng-class="{'userActive': isActiveL, 'userInactive': !isActiveL}" ng-click="isActiveL = !isActiveL">L</a>
<a ng-class="{'userActive': isActiveR, 'userInactive': !isActiveR}" ng-click="isActiveR = !isActiveR">R</a>
<a ng-class="{'userActive': isActiveJ, 'userInactive': !isActiveJ}" ng-click="isActiveJ = !isActiveJ">J</a>

如果您只想使用一个变量

<a ng-class="{'userActive': isActive==1, 'userInactive': isActive!=1}" ng-click="isActive=1">L</a>
<a ng-class="{'userActive': isActive==2, 'userInactive': isActive!=2}" ng-click="isActive=2">R</a>
<a ng-class="{'userActive': isActive==3, 'userInactive': isActive!=3}" ng-click="isActive=3">J</a>

答案 2 :(得分:1)

也许这个:

<ul>
    <li ng-repeat="item in listItems">
        <a ng-class="item.isActive ? 'userActive' : 'userInactive'" ng-click="item.isActive = !item.isActive">{{item.name}}</a>
    </li>
</ul>