Search code examples
javascriptcssangularjsng-class

How to assign class to an element using $scope variable in angular js


I have a class

.haba-haba{
border:1px solid red;
height:50%;
width:50%;
}

I am storing the class name in scope variable in my controller using

$scope.className = "haba-haba";

How can I assign $scope.className to my div as a class?

I tried doing <div ng-class="'{{className:true}}'"></div> It didn't work.

Anyone can tell me a solution? thanks in advance!


Solution

  • The syntax for the ngClass directive is this:

    ng-class="{'haba-haba': thruthValue}"

    where

    $scope.thruthValue = true;

    You can obviously replace true with false or a function that returns true or false.

    Another usage is this:

    ng-class="getTheClass()"

    where

    $scope.getTheClass = function() {
        return 'haba-haba';
    }
    

    Here's a working fiddle of the second usage.

    Also, as other people have pointed out, the second usage is totally against sane MVC. Don't use it unless you know what you are doing.