3

我想应用ng-class唯一button/element被点击的,我该怎么做?

JS文件:

var classApp = angular.module('classApp', []);
classApp.controller('classCtrl', function ($scope) {
    $scope.isActive = false;

    $scope.activeButton = function() { 
       $scope.isActive = !$scope.isActive;         
    }  
});

HTML 文件:

<div ng-app="classApp" ng-controller="classCtrl">
    <button class="button" ng-class="{'active': isActive}" ng-click="activeButton()" type="button">Click Me to Toggle Class</button> 

    <button class="button" ng-class="{'active': isActive}" ng-click="activeButton()" type="button">Click Me to Toggle Class</button> 
</div>

http://codepen.io/anon/pen/BjNyNe

4

2 回答 2

1

这是一个可能的解决方案:

控制器:

classApp.controller('classCtrl', function ($scope) {
    $scope.isActive = [false, false];

    $scope.activeButton = function (index) {     
        $scope.isActive[index] = !$scope.isActive[index];         
    }   
});

和html:

<div ng-app="classApp" ng-controller="classCtrl">
    <button class="button" ng-class="{'active': isActive[0]}" ng-click="activeButton(0)" type="button">Click Me to Toggle Class</button> 

    <button class="button" ng-class="{'active': isActive[1]}" ng-click="activeButton(1)" type="button">Click Me to Toggle Class</button> 
</div>

编辑:我的解决方案有效,但@Shashank Agrawal 解决方案更好更清洁。

于 2015-12-09T12:54:10.970 回答
1

这是 Angular 指令的用途。您可以使用一个简单的指令,而不是维护各种变量:

app.directive('clickActive', [function() {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            element.on('click', function() {
                element.toggleClass("active");
                if (attr.moreClasses) {
                    // Optionally toggle more classes if passed
                    element.toggleClass(attr.moreClasses);
                }
            });
        }
    };
}]);

HTML:

<div ng-app="classApp" ng-controller="classCtrl">
  <button class="button" click-active type="button">Click Me to Toggle Class</button> 

   <button class="button" click-active type="button">Click Me to Toggle Class</button> 
</div>

(可选)传递更多类来切换,例如:

<button class="button" click-active more-classes="foo bar" type="button">Click Me to Toggle Class</button> 
于 2015-12-09T12:55:11.360 回答