简体   繁体   中英

AngularJS - Toggle class on specific button using ng-class directive

Directive

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
};

});

If there are multiple buttons, toggling class is applied to every button.

  1. How do I toggle class to button which is clicked and not every other button using ng-class directive ? ie scope.controlClass should be applied only to button which is clicked.

Use $event

You can pass $event to the doMute function.

So the doMute function become:

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);
        }
}

And your element:

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

Here is my comment as an answer + a response to your feedback:

1) In your JS code, you should use:

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

and:

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

if you want Angular to perform bi-directional binding. Angular's object is $scope and not scope , and NO , scope is NOT a directive.

Last, your HTML should be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM