Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to element using Angular JS

Tags:

angularjs

I know how to add a class on click of a button in 'jQuery'

$('#button1').click(function(){  $('#div1').addClass('alpha'); }); 

I want to achieve same thing by angular js. I have a controller - myController1. Can someone help me do it eazily?

like image 444
Deadpool Avatar asked May 23 '15 08:05

Deadpool


People also ask

Can we use class and ngClass together?

yes , you can do it. Did you try it? What happened? You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

How do you add a class to a given element?

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").


2 Answers

AngularJS has some methods called JQlite so we can use it. see link

Select the element in DOM is

angular.element( document.querySelector( '#div1' ) ); 

add the class like .addClass('alpha');

So finally

var myEl = angular.element( document.querySelector( '#div1' ) ); myEl.addClass('alpha'); 
like image 130
vamsikrishnamannem Avatar answered Oct 18 '22 21:10

vamsikrishnamannem


You can use ng-class to add conditional classes.

HTML

<button id="button1" ng-click="alpha = true" ng-class="{alpha: alpha}">Button</button> 

In your controller (to make sure the class is not shown by default)

$scope.alpha = false; 

Now, when you click the button, the $scope.alpha variable is updated and ng-class will add the 'alpha' class to your button.

like image 32
Daniel Hutton Avatar answered Oct 18 '22 20:10

Daniel Hutton