0

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...

3 Answers 3

1

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');
Sign up to request clarification or add additional context in comments.

1 Comment

thnku for your answer. But i want to add class dynamically in controller. not in html.
1

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');
});

Comments

0

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';
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.