Sibiraj
Sibiraj

Reputation: 4756

ng-class allows assignment operator. is it a bug or feature?

I recently noticed that ng-class allows assignment operator is it a bug or a feature.

<li ng-repeat="cat in cats" ng-class="{active: cat = 'some-text'}">{{cat}}</li>

correct usage

<li ng-repeat="cat in cats" ng-class="{active: cat == 'some-text'}">{{cat}}</li>

also look at the plunk behaviour

Allowing assignment operator is a bug or a feature?

Upvotes: 2

Views: 114

Answers (5)

Sibiraj
Sibiraj

Reputation: 4756

Raised an issue in GitHub and got a clarification

issue : https://github.com/angular/angular.js/issues/16049

issue-comment: https://github.com/angular/angular.js/issues/16049#issuecomment-308092056

Upvotes: 0

Ram_T
Ram_T

Reputation: 8484

{'active': cat === 'some-text'} is correct way to add class and there some-text is just a string and if it matches with the variable cat then active class will be added to li element

Even you can do like this,

ng-class="{(condition) ? 'condition_true_class' : 'condition_false_class'}"

EDIT

<li ng-repeat="cat in cats" ng-class="{active: cat = 'some-text'}">{{cat}}</li>

in this case cat="some-text" returns some-text string which is always true and active class will be added to li element and cat in {{}} becomes some-text as you are using assignment operator.

<li ng-repeat="cat in cats" ng-class="{active: cat == 'some-text'}">{{cat}}</li>

in this case if cat value matches with some-text then active class will be added to li and cat value will not change as you are using logical operator == or ===

Upvotes: 1

31piy
31piy

Reputation: 23859

This is more of a JavaScript expression evaluation, instead of a special Angular thing.

var x;
console.log(!!(x = 'some-text'));

If you see your console, it will always print true. Similarly, ng-class="{active: cat = 'some-text'}" will always assign the class active to the element, since cat = 'some-text' will always return true as its boolean equivalent.

Also, it is notable that cat will be changed to some-text in each iteration. This means that your cats object will be nothing but an array of some-text.

As @Mr_Perfect mentioned in the comments, if you conditionally need to assign active to your elements, change = to ===.

Upvotes: 2

nevradub
nevradub

Reputation: 238

If you need to use class active wiith ng-class try this :

<li ng-repeat="cat in cats" ng-class="{'active': cat == 'some-text'}">{{cat}}</li>

Upvotes: 0

JeanJacques
JeanJacques

Reputation: 1754

It's because, as you assigne a value to cat it's evaluated to true because cat is not null or undifined

Upvotes: 1

Related Questions