Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding & Removing additional class on my element tag

I'm learning Angular.js and at first glimpse I thought it was easy. :P. But I'm stuck here. What I want is to add another class on my <.a>(anchor) tag.

My HTML Code:

<a href="#/services" title="Services" class="scroll">
<a href="#/portfolio" title="Portfolio" class="scroll">

Say when I click the service link it will add "enabled" class

<a href="#/services" title="Services" class="scroll enabled">
<a href="#/portfolio" title="Portfolio" class="scroll">

then if I clicked the portfolio link it will add "enabled" class also and will remove the enabled class from the services anchor tag

<a href="#/services" title="Services" class="scroll">
<a href="#/portfolio" title="Portfolio" class="scroll enabled">

What is the best way to achieve this? Read about ng-click and ng-class, and also does ng-class support ternary operator? Their docs doesn't say anything about that. link

like image 863
Wondering Coder Avatar asked Aug 05 '13 10:08

Wondering Coder


2 Answers

I'm starting with Angular too, and in similar cases i'm using directives , check this out:

yourApp.directive('scroll', function () {        
    return {
    restrict : 'C',
        link: function(scope, element) {
            element.bind("click" , function(e){
                 $("a").removeClass("enabled"); // Here we need jQuery
                 element.addClass("enabled");
            });     
        }
    }
});


UPDATE Hurray , i found a solution without jQuery! element's click handler now looks like this:

element.bind("click" , function(e){
   element.parent().find("a").removeClass("enabled"); // Vanilla jqLite!
   element.addClass("enabled");
}); 

Plunker: http://plnkr.co/edit/jw16wW

like image 81
Ivan Chernykh Avatar answered Sep 30 '22 01:09

Ivan Chernykh


simply add this code inside your angular function to remove class

angular.element(document.querySelector(".yourClass")).removeClass("yourClass");

OR

angular.element(document.querySelector("#yourSelector")).removeClass("#yourSelector");

Thanks

like image 38
Shubham Kandiyal Avatar answered Sep 30 '22 01:09

Shubham Kandiyal