Search code examples
angularjsng-class

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 ?


Solution

  • 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 }