Event handling in angularJS
- 25-07-2022
- Toanngo92
- 0 Comments
directive
With pure javascript or jquery, we often interact with the DOM, like catching click, hover, form submit, tag change events, angularJS provides us with a more concise solution to help us handle these problems. Some directives for event handling in angularJS:
- ng-click
- ng-dbl-click
- ng-keydown
- ng-keyup
- ng-mousedown
- ng-mouseenter
- ng-mouseleave
- ng-change
- ng-submit
- …
See more docs here: https://docs.angularjs.org/api/ng/directive/
We simply need to put the event handling directive in the tag we want to catch the event and define the function to use. See the example below:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello world angular</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body> <div ng-app="calculateApp" ng-controller="calculateController"> <label>Quantity:</label> <input type="number" min="1" max="10" ng-model="qty" /> <label>Price</label> <input type="number" min="0" max="5000" ng-model="price" /> <div>Total: {{total | currency: '$ '}}</div> <button ng-click="calculate()">Calculate</button> </div> <script> var app = angular.module('calculateApp', []); app.controller('calculateController',function($scope){ $scope.qty = 0; $scope.price = 0; $scope.total = 0; $scope.calculate = function(){ this.total = this.qty * this.price; } }); </script> </body> </html>
In this example, we handle the user’s click event through the ng-click directive, which calls the calculate() function. Under the script layer, define the method (method/function) calculate and handle the logic according to the intention we want. The same goes for the rest of the events.
Consider the following example:
<!DOCTYPE html> <html lang="en" ng-app="exampleviewApp"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example View AngularJS</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </head> <body ng-controller="mainController"> <h2>Hello {{name}}</h2> <input type="text" ng-model="name" ng-change="change()" /> {{length}} </body> <script> var exampleviewApp = angular.module('exampleviewApp', []); exampleviewApp.controller('mainController', function($scope) { $scope.name = ''; $scope.length = 0; $scope.change = function(){ $scope.length = $scope.name.length; } }); </script> </html>
Result when running the code:
In the above example, we will see the solution when combining data binding with the change event, the code is very clean, short and the data is updated realtime.