Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-class does not remove a class that was there before angular was bootstrapped

Still under 72 hours coming up to speed with angular. Having used knockout for a while, I have to say it's interesting. My question right now has to do with ng-class.

Say I have the following:

<div class="myClass" ng-class="{myClass: false}">

When angular bootstraps, it does not remove the myClass attribute that was rendered there before. I had expected it to, since that's what ko's css binding does. It seems that angular only removes the class if angular was the one who put it there.

So, is there a common workaround for this? Other than creating a custom directive?

like image 738
danludwig Avatar asked Jan 02 '14 16:01

danludwig


People also ask

Can I use both class and ngClass?

You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

How do I delete a class in typescript?

Remove class from multiple elements with javascriptquerySelector() method passing it the name of element. It will return a collection of div elements. Iterate over these elements and use classList. remove() or className property to remove CSS classes.


1 Answers

Since you're only using Angular for the form and need a class to be active on elements within the form prior to Angular bootstraping it looks like a directive may be the best way to go.

The following directive will remove the specified class from the element its on once the directive is linked in by Angular (which is almost the same point when ngClass will kick in):

.directive('removeClass', function(){
    return {
        restrict: 'A',
        link: function(scope,element, attrs){
            element.removeClass(attrs.removeClass);
        }
    };
});

Used like so:

<div class="oldClass" remove-class="oldClass" ng-class="{newClass: true}">stuff</div>

demo fiddle

like image 70
KayakDave Avatar answered Nov 16 '22 03:11

KayakDave