user2483724
user2483724

Reputation: 2119

How do you add/remove a list of classes from an element?

Most question and answers I've seen related to this say to use ng-class. However, I have a list of many classes of which I need to add 2 of to each element. This is in a directive.

"<div><div class='card {{suit}} {{value}}'></div></div>"

I don't think listing out every class with ng-class with a boolean is viable here. Is there an angular way of removing and adding classes?

Something like:

link: (scope,elem,attrs){
    elem.firstChild().removeAllClasses();
    elem.firstChild().addClass(attr.suit, attr.value, "card");
}

Upvotes: 2

Views: 3776

Answers (1)

SoluableNonagon
SoluableNonagon

Reputation: 11755

If the code is in your directive, you can just use jqLite.

link: (scope,elem,attrs){
    elem.removeAttr('class');
    elem.addClass(attr.suit);
    elem.addClass(attr.value);
    elem.addClass("card");
}

here is a list of all the supported jqlite functions

https://docs.angularjs.org/api/ng/function/angular.element

Upvotes: 5

Related Questions