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?
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.
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With