Angular ng-class setting proper class (confirmed in page source) but won't apply styles

StackOverflow https://stackoverflow.com//questions/25068248

  •  26-12-2019
  •  | 
  •  

Question

Yes...it's tabular data.

So, the question title explains most of what is going on but I'll provide a few more specifics: I have a model on my controller that contains properties "Name" and "Value"(with possibilities"GOOD" and "BAD")

I have 2 classes defined in my SCSS file to provide styles for "valid" and "invalid" values.

SCSS pseudo.

&[class *= "Foo"]
{
  color: green;
}
&[class *= "Bar"]
{
  color: red;
}

Markup

<ul ng-controller="thingsController">
   <li ng-repeat="thing in things">
      <table >
         <tr >
            <td>{{thing.name}}</td>
            <td ng-class="{'Foo' : true}">{{thing.value}}</td>
         </tr>
      </table>
   </li>
</ul>

Ok, so the crux of this: If I use:

<td class="Foo">{{thing.value}}</td>

it renders value with green text color. If I use:

<td class="Bar">{{thing.value}}</td>

it renders value with red text color.

HOWEVER, If I use:

<td ng-class="{'Foo':true}">{{thing.value}}</td>

It renders value with black (default) colored text. (Same for Bar)

When I inspect my element in Chrome Dev Tools, I see

<td ng-class="{'Foo':true" class="ng-binding Foo">GOOD</td>

but if I inspect the styles tab, the styles within Foo have not been applied to my element...it's nowhere in my cascade.

Can anyone tell what's up with that?

Was it helpful?

Solution

I've found the cause. It is related to using regex selectors to build a block__element--modifier css structure.

ng-class apparently does not respect the "begins with" css selector.

[class ^= "block"]
{
  &[class *= "__element"]
  {
    &[class *= "--modifier"]
    {

    }
  }
}

I had to change the initial [class ^= "block"] to [class *= "block"] which is absolute crap...but ng-class was able to do what it is supposed to do.

Edit

The reason that the "Begins With" css selector cannot be used with ng-class is that "begins with" performs a whole string comparison on the value of class.

ng-binding

gets prepended by Angular to the classes that get applied through the ng-class directive, so the class becomes

class="ng-binding foo"

...which does not begin with foo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top