AngularJS - 使用ng-class指令在特定按钮上切换类

时间:2016-08-29 12:56:12

标签: javascript angularjs angularjs-directive ng-class

指令

myApp.directive('vlcObject', function ($compile, $rootScope, $timeout, $window) {
var vlcPlayerId = '';
var linker = function (scope, element, attrs) {

scope.muteClass = 'fa fa-volume-on';

<button id=mute_uniqId ng-click="doMute(uniqId)"><i ng-class="muteClass"></i></button>

scope.doMute = function(uniqId){
    var vlc = scope.getVLC("vlc");
     if (vlc && vlc.playlist.isPlaying) {
        vlc.audio.toggleMute();
        scope.controlClass = 'fa fa-volume-off';
    }else{
        scope.controlClass = 'fa fa-volume-on';
    }
}

};
return {
    restrict: "E",
    link: linker
};

});

如果有多个按钮,则每个按钮都会应用切换类。

  1. 如何使用ng-class指令将类切换到单击的按钮而不是每个其他按钮?即scope.controlClass应仅应用于单击的按钮。

2 个答案:

答案 0 :(得分:0)

使用$ event

您可以将$ event传递给doMute函数。

所以doMute函数变为:

scope.nomuteClass = 'fa fa-volume-on';
scope.muteClass = 'fa fa-volume-off';
scope.doMute = function(uniqId, event){
        var vlc = scope.getVLC("vlc");
         if (vlc && vlc.playlist.isPlaying) {
            vlc.audio.toggleMute();
            angular.element(event.target).children().removeClass(scope.muteClass).addClass(scope.nomuteClass);
        } else{
            angular.element(event.target).children().removeClass(scope.nomuteClass).addClass(scope.muteClass);
        }
}

你的元素:

<button id=mute_uniqId ng-click="doMute(uniqId, $event)"><i></i></button>

答案 1 :(得分:0)

以下是我的评论作为答案+对您的反馈的回复:

1)在你的JS代码中,你应该使用:

$scope.doMute = function(...) {...} ;

$scope.muteClass = 'fa fa-volume-on';

如果您希望Angular执行双向绑定。 Angular的对象是$scope而不是scope,而 NO scope NOT 指令。

最后,您的HTML应为:

<button id=mute_uniqId ng-click="doMute(uniqId)"><i ng-class="{{muteClass}}"></i></button>