Subhranshu
Subhranshu

Reputation: 445

Angular Expression Interpolation

I came through the following example of ng-class="expression" in a book. http://plnkr.co/edit/fJGT5L9HZXvgAiAyXwlW?p=preview

ng-class="{error:isError,warning:isWarning}"

I get the controller logic, but my doubt is in the interpolation happening here.

What does the following scenarios mean (what is the evaluated value) and Why?

  1. ng-class="{error:true,warning:true}"
  2. ng-class="{error:true,warning:false}"
  3. ng-class="{error:false,warning:true}"
  4. ng-class="{error:false,warning:false}"

Upvotes: 0

Views: 865

Answers (3)

Max
Max

Reputation: 1844

  1. ng-class="{error:true,warning:true}" => class="error warning"
  2. ng-class="{error:true,warning:false}" => class="error"
  3. ng-class="{error:false,warning:true}" => class="warning"
  4. ng-class="{error:false,warning:false}" => no classes set

As you could notice ng-class get just hash where keys are names of classes and values -- conditions (if true than class will be added to class attribute)

So, ng-class just uses angular expression and check what data it returns (string, array or hash-map) then it applies certain parser to get final classes array to put it to class. One of this is described above.

Angular expressions

Angular like as Javascript uses eval mechanism to execute code (expression), but unlike JS Angular uses safe eval called $eval([expression], [locals]) (Docs)

I'm strongly recommending you to read this article about Angular expressions to understand how it works.

Upvotes: 2

Catalin MUNTEANU
Catalin MUNTEANU

Reputation: 5634

From the ngClass arguments docs:

The result of the arguments evaluation can be a string representing space delimited class names, an array, or a map of class names to boolean values. In the case of a map, the names of the properties whose values are truthy will be added as css classes to the element.

So in your case the result of the arguments after evaluation is a map which produces:

ng-class="{error:true,warning:true}"
=> class="error warning"

ng-class="{error:true,warning:false}"
=> class="error"

ng-class="{error:false,warning:true}"
=> class="warning"

ng-class="{error:false,warning:false}"
=> no class attribute

Upvotes: 2

Jason
Jason

Reputation: 15931

Angular will add (or append to the existing class attr) the following class attribute to the element:

  1. class="error warning"
  2. class="error"
  3. class="warning"
  4. No class attribute added

Upvotes: 1

Related Questions