6

我有几个按钮可以像切换器一样工作。如果您单击一个,它会变为活动状态并“关闭”其他按钮。我使用 jQuery 做到了这一点,但想使用 AngularJS。这是我的代码:

HTML

<div class="button-bar">
    <a class="button button-energized" id="weak">weak</a>
    <a class="button button-energized" id="normal">normal</a>
    <a class="button button-energized" id="strong">strong</a>
</div>

JavaScript

    .controller('AppCtrl', function($scope, $stateParams) {

        $('#weak').click(function() {
            $('#weak').addClass('active');
            $('#normal').removeClass('active');
            $('#strong').removeClass('active');
        });

        $('#normal').click(function() {
            $('#normal').addClass('active');
            $('#weak').removeClass('active');
            $('#strong').removeClass('active');
        });

        $('#strong').click(function() {
            $('#strong').addClass('active');
            $('#normal').removeClass('active');
            $('#weak').removeClass('active');
        });

   });
4

2 回答 2

21

您可以拥有ng-click可以切换selected标志,可以ng-class用于绑定/取消绑定类。

标记

<div class="button-bar">
    <a class="button button-energized" id="weak" 
       ng-class="{active: $parent.selected=='weak'}" ng-click="$parent.selected='weak'">
      weak
    </a>
    <a class="button button-energized" id="normal" 
       ng-class="{active: selected=='normal'}" ng-click="selected='normal'">
        normal
    </a>
    <a class="button button-energized" id="strong" 
       ng-class="{active: selected=='strong'}" ng-click="selected='strong'">
        strong
    </a>
</div>

工作小提琴

更好的方法

您可以通过使用 which 来轻松地做到这一点,ng-repeat这将减少您的代码行。

标记

$scope.strengths = ["weak","normal","strong"];

代码

<div class="button-bar">
    <a class="button button-energized" id="{{strength}}" 
       ng-class="{active: $parent.selected == strength}" 
       ng-click="$parent.selected=strength"
       ng-repeat="strength in strengths">
      {{strength}}
    </a>
</div>
于 2015-08-07T08:02:13.540 回答
1

您可以使用

angular.element(document.querySelector("#cntrlID")).removeClass("customclass");

HTML:

<div class="button-bar">
    <a class="button button-energized" id="weak" ng-click=removeNS()>weak</a>
    <a class="button button-energized" id="normal" ng-click=removeWS()>normal</a>
    <a class="button button-energized" id="strong" ng-click=removeWN()>strong</a>
</div>

$scope.removeNS = function(){
    angular.element(document.querySelector("#normal")).removeClass("active");
    angular.element(document.querySelector("#strong")).removeClass("active");
}
$scope.removeWS = function(){
    angular.element(document.querySelector("#weak")).removeClass("active");
    angular.element(document.querySelector("#strong")).removeClass("active");
}
$scope.removeWN = function(){
    angular.element(document.querySelector("#weak")).removeClass("active");
    angular.element(document.querySelector("#normal")).removeClass("active");
}

进一步优化,您可以只创建一个函数并传递查询选择器和要删除的类作为函数参数,例如:

function(id1,id2,removeClassName)
于 2017-06-27T07:30:11.127 回答