AngularJS - SPLessons

AngularJS Events

Chapter 19

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

AngularJS Events

AngularJS Events

shape Description

After creating the basic Directive that simply displays data, the next step is to start adding some inner activity to the directives through AngularJS Events. Handling events is the job of functions on scope, which will require a controller. These three pieces play an integral part in making you directives interactive.

When developing advanced AngularJS applications, application may need to interact with mouse clicks, keyboard inputs, moves, events change, etc. at some point. AngularJS Events helps to handle all such events by giving a simple model to add events to DOM elements. AngularJS has built-in event directives that are associated with HTML DOM elements. It generates output from HTML view page. Here, an explanation on how to use AngularJS Events in developing applications. 

shape Example

Below is an example for ng-click directive.

<!DOCTYPE html>
<html lang="en-US">

  <head>
    <title>ng-click directive</title>
    <script data-require="angular.js@1.3.14" data-semver="1.3.14" src="https://code.angularjs.org/1.3.14/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src="App.js"></script>
    <script src="Controller.js"></script>
  </head>

  <body ng-app="spApp">
    <h1>ng-click directive</h1>
    <div ng-app="spApp" ng-controller="SPController">
      <div ng-click="data.onClick()">Click here</div>
    </div>
  </body>

</html>
 angular.module("spApp", [])
 .controller("SPController", function($scope) {
   $scope.data = {};
   $scope.data.onClick = function() {
    alert("clicked");
   }
 } );

When clicked on the inner div in the above example, the function data.onClick() is called.the data object has a onClick() function added to it in the controller function. Below is the result.

The controller function adds event listener functions called to the $scope object.
Output:

When Clicked on “Click Here”, the below output appears.

shape More Info

The event listener directives have an uncommon variable called $event,.This $event acts as parameter to the event listener function. The $event variable contains the original browser event object.

shape Example

<!DOCTYPE html>
<html lang="en-US">

<head>
  <title>Browser event object</title>
</head>

<body ng-app="spApp">
  <h1>Browser event object</h1>

  <div ng-controller="SPController" >
     <div ng-click="data.onClick($event)">Click here</div>
  </div>

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  <script src="App.js"></script>
  <script src="Controller.js"></script>
</body>

</html>
 angular.module("myapp", [])
 .controller("SPController", function($scope) {
   $scope.data = {};
   $scope.data.onClick = function(event) {
   alert("clicked: " + event.clientX + ", " + event.clientY);
   }
 } );

Output:

When clicked on the text “Click Here” the below output appears.

Mouse Events

shape Description

When the cursor moves over an element mouse events occur and, will be in the below order:

  • ng-mouseenter
  • ng-mouseover
  • ng-mousemove
  • ng-mouseleave

When a mouse button is clicked on an element,the events occurrence will be in the below order:

  • ng-mousedown
  • ng-mouseup
  • ng-click

These mouse events can be applied on any HTML element.

shape Example

Below is an example determining the functionality of all mouse events.

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.3.14" data-semver="1.3.14" src="https://code.angularjs.org/1.3.14/angular.js"></script>
    <script src="angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="mainModule">
    <div ng-controller="mainController">
      
      <h3>1. Click</h3>
      <button id="firstBtn" ng-click="onFirstBtnClick()">Click me</button>
      
        {{onFirstBtnClickResult}}     
        
       <br /><br />
       
      <h3>2. Click with Dependency Injection</h3>
      <label>Type here:<input type="text" ng-model="secondBtnInput" /></label>
      <button id="secondBtn" ng-click="onSecondBtnClick(secondBtnInput)">Click me</button>
        <br />
  
        {{onSecondBtnClickResult}}    
       
        <br />  <br />
      
      <h3>3. Double click</h3>

        Double-click on the below image to see the result<br><br>
        <img src="https://www.splessons.com/wp-content/uploads/2015/06/splessons.png" ng-dblclick="onDblClick()" />
        
        <br /><br />

         {{onDblClickResult}}    
         
      <h3>4. Mouse down, up, enter, leave, move, over</h3>

        Move the mouse on the square  <br /><br/>
        
      <img src="https://www.splessons.com/wp-content/uploads/2015/06/splessons.png" ng-mousedown="onMouseDown($event)" ng-mouseup="onMouseUp($event)" ng-mouseenter="onMouseEnter($event)" ng-mouseleave="onMouseLeave($event)" ng-mousemove="onMouseMove($event)" ng-mouseover="onMouseOver($event)" />
      
      <br /><br />
      
      <strong>MOUSE DOWN RESULT:</strong>
         {{onMouseDownResult}}      <br /><br />
         
      <strong>MOUSE UP RESULT:</strong>
         {{onMouseUpResult}}      <br /><br />
         
      <strong>MOUSE ENTER RESULT:</strong>
         {{onMouseEnterResult}}      <br /><br />
         
      <strong>MOUSE LEAVE RESULT:</strong>
         {{onMouseLeaveResult}}      <br /><br />
 
      <strong>MOUSE MOVE RESULT:</strong>
         {{onMouseMoveResult}}      <br /><br />
 
      <strong>MOUSE OVER RESULT:</strong>
         {{onMouseOverResult}}
         
    </div>
  </body>

</html>

script.js

angular.module("mainModule", [])
  .controller("mainController", function ($scope)
  {
    // Initialization
    $scope.onFirstBtnClickResult = "";
    $scope.secondBtnInput = "";
    $scope.onDblClickResult = "";
    $scope.onMouseDownResult = "";
    $scope.onMouseUpResult = "";
    $scope.onMouseEnterResult = "";
    $scope.onMouseLeaveResult = "";
    $scope.onMouseMoveResult = "";
    $scope.onMouseOverResult = "";

    // Utility functions

    // Accepts a MouseEvent as input and returns the x and y
    // coordinates relative to the target element.
    var getCrossBrowserElementCoords = function (mouseEvent)
    {
      var result = {
        x: 0,
        y: 0
      };
      
            if (!mouseEvent)
      {
        mouseEvent = window.event;
      }

      if (mouseEvent.pageX || mouseEvent.pageY)
      {
        result.x = mouseEvent.pageX;
        result.y = mouseEvent.pageY;
      }
      else if (mouseEvent.clientX || mouseEvent.clientY)
      {
        result.x = mouseEvent.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
        result.y = mouseEvent.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
      }

      if (mouseEvent.target)
      {
        var offEl = mouseEvent.target;
        var offX = 0;
        var offY = 0;

        if (typeof(offEl.offsetParent) != "undefined")
                {
          while (offEl)
          {
            offX += offEl.offsetLeft;
            offY += offEl.offsetTop;

            offEl = offEl.offsetParent;
          }
        }
        else
        {
          offX = offEl.x;
          offY = offEl.y;
        }

        result.x -= offX;
        result.y -= offY;
      }

      return result;
    };

    var getMouseEventResult = function (mouseEvent, mouseEventDesc)
    {
      var coords = getCrossBrowserElementCoords(mouseEvent);
            return mouseEventDesc + " at (" + coords.x + ", " + coords.y + ")";
    };

    // Event handlers
    $scope.onFirstBtnClick = function () {
      $scope.onFirstBtnClickResult = "CLICKED";
    };

    $scope.onSecondBtnClick = function (value) {
      $scope.onSecondBtnClickResult = "you typed '" + value + "'";
    };

    $scope.onDblClick = function () {
      $scope.onDblClickResult = "DOUBLE-CLICKED";
    };

    $scope.onMouseDown = function ($event) {
          $scope.onMouseDownResult = getMouseEventResult($event, "Mouse down");
    };

    $scope.onMouseUp = function ($event) {
      $scope.onMouseUpResult = getMouseEventResult($event, "Mouse up");
    };

    $scope.onMouseEnter = function ($event) {
      $scope.onMouseEnterResult = getMouseEventResult($event, "Mouse enter");
    };

    $scope.onMouseLeave = function ($event) {
      $scope.onMouseLeaveResult = getMouseEventResult($event, "Mouse leave");
    };

    $scope.onMouseMove = function ($event) {
      $scope.onMouseMoveResult = getMouseEventResult($event, "Mouse move");
    };

    $scope.onMouseOver = function ($event) {
      $scope.onMouseOverResult = getMouseEventResult($event, "Mouse over");
    };
  });

Output:

Summary

shape Key Points

  • AngularJS has built-in event directives that are associated with HTML DOM elements.
  • The controller function adds the event listener functions called to the $scope object.
  • $event object can be added as an argument when calling the function.