仅对

时间:2015-12-09 12:45:44

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

我想仅在点击的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

2 个答案:

答案 0 :(得分: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 solution更好更清洁。

答案 1 :(得分:1)

以下是Angular Directives的用法。 您可以使用简单的指令来代替维护各种变量:

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>