himanshu
himanshu

Reputation: 208

ng-class with Evaluated Expression not working with class name passed as variable

This is my html

    <div ng-class="getClasses()"> </div>

The getClasses() method enter code here defined in controller as

    $scope.getClasses = function () {

   //another function call to get class name

   //To make short what ever the function returns it stores to variable 
     className i.e. 

    var className = 'proSpacerOne';

   //Similarly let

    var alternateClass = 'proSpacerOneA';


    return { className: false, alternateClass: true};
}

Here as my expectation 'proSpacerOneA' class should be applied to the But its applying class with name 'alternateClass'.

However if return the hard coded class name its working fine.

  return { 'proSpacerOne': false, 'proSpacerOneA': true};

What's wrong if I pass class name as variable ?

Upvotes: 1

Views: 784

Answers (3)

Tamer Aktaş
Tamer Aktaş

Reputation: 425

when angular trying to render

  ng-class="getClasses()"

expression, its fill class atribbute with retured object keys if value is not hoist false.

So if you return

{ className: false, alternateClass: true};

from your function angular will render class html tag like this

class="alternateClass"

you should use a different logic to pass class names to ng-class expression. A valueable tutorail attached here

Upvotes: 0

Mistalis
Mistalis

Reputation: 18269

To use a variable as an object key, you have to use the[] synthax.

Change:

return { className: false, alternateClass: true};

To

var returnObj = {};
returnObj[className] = false;
returnObj[alternateClass] = true;
return returnObj;

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You need to use bracket notation:

var className = 'proSpacerOne';
var alternateClass = 'proSpacerOneA';
var obj = {}
obj[className] = false;
obj[alternateClass] = true;

return obj;

Or ES6 object initializer (http://www.ecma-international.org/ecma-262/6.0/#sec-object-initializer):

return { [className] : false, [alternateClass] : true }

Upvotes: 1

Related Questions