59

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?

Deadpool
  • 7,811
  • 9
  • 44
  • 88

9 Answers9

97

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');
vamsikrishnamannem
  • 4,817
  • 5
  • 23
  • 34
35

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.

Daniel Hutton
  • 1,455
  • 1
  • 17
  • 33
  • 2
    Didn't work until I added ' ' around the class (first alpha). Also why make the boolean variable same name as the class, could be confusing to some people. Downvote – Jaad Chacra Nov 21 '17 at 23:18
24

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

Community
  • 1
  • 1
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
5

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

Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
5

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.

jad-panda
  • 2,509
  • 16
  • 22
2

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"); 
        }
    }
}
whale_steward
  • 2,088
  • 2
  • 25
  • 37
Nammen8
  • 619
  • 1
  • 11
  • 31
1

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>
chainstair
  • 681
  • 8
  • 18
1

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;
}
Ronald Babu
  • 166
  • 1
  • 7
-1

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

  • Why? Please add some explanation to your code such that others can learn from it – Nico Haase Mar 13 '19 at 08:18
  • Note: Keep in mind that this function will not find elements by tag name / CSS selector. For lookups by tag name, try instead angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll(). – nayan zala Mar 13 '19 at 12:09
  • 1
    Please do not copy&paste content from other sites without proper attribution. Rather explain the code you've written, and why that solves the problem – Nico Haase Mar 13 '19 at 12:47
  • not a copy this code this create me and refer a angular js officeal site – nayan zala Mar 14 '19 at 04:37
  • You created that last line (starting with "Note") and contributed it to the AngularJS documentation? Ok, didn't know that. But then you should be able to explain further how exactly your code solves the problem - just have a look at the other answers that contain nearly the same code – Nico Haase Mar 14 '19 at 06:26