How to add event listeners in HTML using AngularJS?


In AngularJS, events help us to perform particular tasks, based on the action. AngularJS is rich in events and has a simple model for adding event listeners to the HTML. AngularJS supports many events related to the mouse and keyboard. All these events are applied to the HTML elements.

In angularJs, we have many HTML events. Suppose we write both AngularJS and HTML events simultaneously. AngularJS event and HTML event will be executed and AngularJS event will not overwrite the HTML event.

Events can be represented by using directives. Like ng-click, ng-change, ng-mousedown, ng-mouseup, ng-keydown, ng-keyup, ng-keypress, ng-mouseover, ng-paste etc.

Let’s see some examples below.

AngularJS ng-click Directive

This directive will be executed when the element is clicked.

Syntax

<element ng-click="expression"></element>

Example

<!DOCTYPE html>
<html>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
   <body>
      <div ng-app="sampleApp" ng-controller="sampleCtrl">
         <h2>ng-click example</h2>
         <button ng-click="addUser()">Add</button>
         <br/><br/>
         <label>Number of users added</label>
         <p>{{ users }}</p>
      </div>
      <script>
         var app = angular.module('sampleApp', []);
         app.controller('sampleCtrl', function($scope) {
            $scope.users = 0;
            $scope.addUser = function() {
               $scope.users++;
            }
         });
      </script>
   </body>
</html>

Here, we click on add button, for each click user count will be increased by one.

AngularJS ng-change Directive

This directive helps us to tell changes in the values of the HTML elements. If we want to work with the ng-change directive, we need to add the ng-model directive also.

Syntax

<element ng-change="expression">
   Contents...
</element>

Example

<!DOCTYPE html>
<html>
   <head>
      <title>ng-change example</title>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
      </script>
      <script type="text/javascript">
         var app = angular.module('sampleApp', []);
         app.controller('sampleCtrl', function ($scope) {
            $scope.show = function () {
               $scope.result = $scope.check == true ? true : false;
            }
         });
      </script>
   </head>
   <body>
      <div ng-app="sampleApp" ng-controller="sampleCtrl">
         <h2>ng-change example</h2>
         Check to show/hide details
         <input type="checkbox" ng-change="show()"-ng-model="check">
         <br><br>
         <div style="padding:10px;
            border:1px solid black;
            width:30%;color:blue"
            ng-show='result'>
            Hello world!
         </div>
      </div>
   </body>
</html>

Using ng-model and ng-change gives us to track HTML elements changes when the user click on the elements.

In the above, we saw an example for the ng-click and ng-change events in HTML. Now let’s check how to add event listeners in AngularJS.

In angularjs, we have a method to add or remove event listeners. Like addEventListener() method and removeEventListener() method.

The addEventListener() Method

This method helps us to attach an event handler to the specified elements. We can use many event handlers for the same element. This method also helps us know how the event reacts to bubbling. About event bubbling, we learn later. Let’s see an example below for the addEventListener() method.

Syntax

element.addEventListener(event, listener, useCapture);

Parameters

  • event can be any valid JavaScript event. Events like using “click” instead of “onclick” or “mousedown” instead of “onmousedown”.

  • listener(handler function), It can be a JavaScript function that responds to that event occurs.

  • useCapture − It is an optional parameter used to control event propagation. A boolean value is passed where “true” denotes capturing phase and “false” denotes the bubbling phases.

Example

<!DOCTYPE html>
<html>
   <body>
      <h2>addEventListener() method</h2>
      <p>Show text when clicks on button</p>
      <button id="btn">Try it</button>
      <p id='showText'></p>
      <script>
         document.getElementById("btn").addEventListener("click", function() {
            document.getElementById('showText').innerHTML = "Hello!"
         });
      </script>
   </body>
</html>

When we click the button, the text will be displayed. Because we attached click event listener on button element.

We can also attach other events like mouseover, mouseout, change, keyup, keypress etc. We can also event handlers to the window object.

Event Bubbling

We know, we have two event propagations i.e. event bubbling and event capturing. Propagation means the way of defining flow of event when event occurs.

Bubbling is the innermost event occurs first and later the outer one. Like, from the child to the parent elements flow.

The removeEventListener() Method

This method helps us to remove attached event handlers from the element.

Example

<!DOCTYPE html>
<html>
   <body>
      <h2>JavaScript removeEventListener()</h2>
      <div id="sampleDiv">
         <p>Click the button to remove the event handler.</p>
         <button onclick="removeHandler()" id="myBtn">Remove</button>
      </div>
      <p id="demo"></p>
      <script>
         document.getElementById("sampleDiv").addEventListener("mousemove", myFunction);
         function myFunction() {
            document.getElementById("demo").innerHTML = Math.random();
         }
         function removeHandler() {
            document.getElementById("sampleDiv").removeEventListener("mousemove", myFunction);
         }
      </script>
   </body>
</html>

This is example for mouseover event handler. When you mouse over on the remove button, it will display some random number. For every hover it will display a random number. When we click on the remove button it will remove the mouseover event handler from the element. Like this, we can simply remove attached event handlers from the elements.

In above, we discussed what the events in AngularJS are. How to add event handlers and remove attached event handlers from the DOM elements using AngularJS methods i.e. addEventListener() and removeEventListener() methods.

Updated on: 21-Feb-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements