Creights
Creights

Reputation: 917

Problems using ng-class to switch a class on ng-click function

Could somebody please tell me where this is going wrong? I basically have a simple check of a value - if the value is true, it should set the class to headerOn. If false, it should be headerOff. Easy. Here's the code:

<div ng-class="headerCheck ? 'headerOn' : 'headerOff'">

And the function that I hit:

$scope.headerControl = function() {

    $scope.headerCheck = true;

    console.log($scope.headerCheck);
}

I can confirm that the log is true. Any ideas why this isn't working for me?

Upvotes: 0

Views: 23

Answers (3)

Burn_E99
Burn_E99

Reputation: 1098

What you have is correct, but you are not telling angularjs that it needs to evaluate what is in the "" as an angular expression. As Karthik stated, you could change the div to

<div ng-class="{headerCheck ? 'headerOn' : 'headerOff'}">

which then makes headerCheck ? 'headerOn' : 'headerOff' an angularjs expression.

EDIT:

Since you did not give a chunk of your code and only gave you snippet, you may want to make sure that the div you referenced in your question is being controlled by the same controller that has your $scope.headerControl function included in.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

The syntax for ng-class is wrong, it should be:

ng-class="{'headerOn' : headerCheck, 'headerOff' : !headerCheck}"

Upvotes: 1

Karthik
Karthik

Reputation: 1377

The problem is the syntax here.

The correct approach would be these:

<div class="{{headerCheck ? 'headerOn' : 'headerOff'}}">

or

<div ng-class="{'headerOn': headerCheck, 'headerOff' : !headerCheck }">

Upvotes: 3

Related Questions