Adding class to element using Angular JS

Angularjs

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

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

Solution 2 - Angularjs

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.

Solution 3 - Angularjs

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

Solution 4 - Angularjs

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

Solution 5 - Angularjs

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.

Solution 6 - Angularjs

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

Solution 7 - Angularjs

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>

Solution 8 - Angularjs

In HTML

To add the class named alpha, assign any variable like showAlpha to false first and then set it to true on click.

<div data-ng-class="{'alpha' : showAlpha}"> </div>

<button ng-click="addClass()"> </button>

In JS file

$scope.showAlpha = false;

$scope.addClass = function(){
   $scope.showAlpha = true;
}

Solution 9 - Angularjs

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()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeadpoolView Question on Stackoverflow
Solution 1 - AngularjsvamsikrishnamannemView Answer on Stackoverflow
Solution 2 - AngularjsDaniel HuttonView Answer on Stackoverflow
Solution 3 - AngularjsJossef Harush KadouriView Answer on Stackoverflow
Solution 4 - AngularjsDeenadhayalan ManoharanView Answer on Stackoverflow
Solution 5 - Angularjsjad-pandaView Answer on Stackoverflow
Solution 6 - AngularjsNammen8View Answer on Stackoverflow
Solution 7 - AngularjschainstairView Answer on Stackoverflow
Solution 8 - AngularjsRonald BabuView Answer on Stackoverflow
Solution 9 - Angularjsnayan zalaView Answer on Stackoverflow