[angularjs] Adding class to element using Angular JS

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?

This question is related to angularjs

The answer is


try this code

<script>
       angular.element(document.querySelectorAll("#div1")).addClass("alpha");
</script>

click the link and understand more

Note: Keep in mind that angular.element() function will not find directly select any documnet location using this perameters angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll()


First thing, you should not do any DOM manipulation in controller function. Instead, you should use directives for this purpose. directive's link function is available for those kind of stuff only.

AngularJS Docs : Creating a Directive that Manipulates the DOM

app.directive('buttonDirective', function($timeout) {
  return {
    scope: {
       change: '&'
    },
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        $timeout(function() {
          // triggering callback
          scope.change();
        });
      });
    }
  };
});

change callback can be used as listener for click event.


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.


Use the MV* Pattern

Based on the example you attached, It's better in angular to use the following tools:

  • ng-click - evaluates the expression when the element is clicked (Read More)
  • ng-class - place a class based on the a given boolean expression (Read More)

for example:

<button ng-click="enabled=true">Click Me!</button>

<div ng-class="{'alpha':enabled}"> 
    ...
</div>

This gives you an easy way to decouple your implementation. e.g. you don't have any dependency between the div and the button.

Read this to learn about the MV* Pattern


Try this..

If jQuery is available, angular.element is an alias for the jQuery function.

var app = angular.module('myApp',[]);

app.controller('Ctrl', function($scope) {

    $scope.click=function(){

      angular.element('#div1').addClass("alpha");
    };
});
<div id='div1'>Text</div>
<button ng-click="click()">action</button>

Ref:https://docs.angularjs.org/api/ng/function/angular.element


For Angular 7 users:

Here I show you that you can activate or deactivate a simple class attribute named "blurred" with just a boolean. Therefore u need to use [ngClass].

TS class

blurredStatus = true

HTML

<div class="inner-wrapper" [ngClass]="{'blurred':blurredStatus}"></div>

querySelector is not from Angular but it's in document and it's in all DOM elements (expensive). You can use ng-class or inside directive add addClass on the element:

myApp.directive('yourDirective', [function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            // Remove class
            elem.addClass("my-class"); 
        }
    }
}