Reputation: 47
I have a div like this
<div ng-model="star"></div>
I want to add a class 'active' to this div in angular js. I tried like this in my angular js controller
$scope.star.addClass('active');
But,I am getting error. I am new to angular js. please help me...
Upvotes: 0
Views: 148
Reputation: 53
If you want to access change class dynamically then you can put watch on your star variable in your controller like below :
$.watch('star',function(newVal, oldVal){
// put your code to here based on new value and old value
// you can add class to your div like :
// angular.element("div[ng-bind='star']").addClass('active');
});
Upvotes: 1
Reputation: 393
Using a variable to control your class
<div ng-class="customClass"></div>
in controller
$scope.customClass = 'active custom-class1';
so, you can use if-else to change class name
if (something) {
$scope.customClass = 'active custom-class1';
} else {
$scope.customClass = 'deactive custom-class2';
}
Upvotes: 0
Reputation: 1768
Try this:
<div ng-class="{ active: star == 'yes', 'in-active': star == 'no' }" ng-bind="star"></div>
You can have one or more classes assigned based on the expression (true or false). If a class name has a hyphen, enclose in single quote. This is a better approach and preferred than changing in controller. Also, because this is a div, you have to do ng-bind, not ng-model. ng-model works on fields like input.
UPDATE:
Since you insist on changing the class in code, here it is:
$("div[ng-bind='star']").addClass('active');
Upvotes: 1