...">

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 injects the code given here in the 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 of the proSpacerOneA class should apply to But its applying a class named "alternateClass".

However, if you return the hard coded class name, it works fine.

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

      

What is wrong if I pass the class name as a variable?

+3


source to share


3 answers


You need to use parenthesis 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 }

      

+1


source


To use a variable as an object key, you must use the syntax []

.

Edit:

return { className: false, alternateClass: true};

      



For

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

      

0


source


when angular tries to render

  ng-class="getClasses()"

      

expression, its atribbute padding class with the keys of the stored objects, unless the value is false false.

So if you come back

{ className: false, alternateClass: true};

      

from your angular function will render the class html tag like this

class="alternateClass"

      

you have to use different logic to pass the class names to the ng-class expression. The value tutorail is attached here

0


source







All Articles