Angularjs Examples

AJS Examples


AngularJS $scope.$on() Function

The AngularJS $on method is used to listens dispatched events of a given type. The $on method catches the event dispatched by $broadcast and $emit methods.

Syntax

$scope.$on(name, listener);
  • In the $on method name is the event name. This watchExpression is called on every $digest() and returns the value that is being watched.
  • In the $watch method listener is a function that is called when the value of the $scope property are not equal to previous value. If the watchExpression is equal to previous value then listener will not be called.
  • In the $watch method objectEquality is a boolean type and used for object equality using angular.equals instead of comparing for reference equality.

AngularJS $scope.$on() Function Example

<!DOCTYPE html>
<html ng-app="app">
<head> <!-- www.techstrikers.com -->
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script> 
  <meta charset="utf-8">          
    <title>AngularJS $broadcast,$emil with $on Example</title>
  <script>
    var app = angular.module('app', []);
    app.controller("ParentController",
      function($scope) {
        $scope.emitClicked = function(msg) {
           $scope.$emit('event', { message: msg });
        };
        $scope.broadcastClicked = function(msg) {
         $scope.$broadcast('event', { message: msg });
        };
      });

    app.controller("ChildController",
      function($scope) {
        $scope.$on('event', function(event, args) {
          $scope.ChildMessage  = 'From Child Controller: ' + args.message;
        });

      });

    app.controller("GrandParentController",
      function($scope) {
        $scope.$on('event', function(event, args) {
          $scope.GrandParentMessage  = 'From GrandParent Controller: ' + args.message;
        });
      });
  </script>
</head>
<body style="background-color:#DDE4E9;">
<fieldset style="background-color:#DDE4E9;">                      
    <legend>AngulerJS $broadcast,$emil with $on method Example</legend> 
  <div ng-controller="GrandParentController">
    <p style="font-family:Arial;color:yellow;background:steelblue;padding:3px;width:350px;">  
            {{GrandParentMessage}}  
          </p>
    <div ng-controller="ParentController">
      <input ng-model="msg" placeholder="Enter Message">
      <button ng-click="emitClicked(msg)">
        $emit
      </button>
      <button ng-click="broadcastClicked(msg)">
        $broadcast
      </button>
      <div ng-controller="ChildController">
            <p style="font-family:Arial;color:yellow;background:steelblue;padding:3px;width:350px;">  
            {{ChildMessage}}  
          </p>
      </div>
    </div>
  </div>
   </fieldset> 
</body>

</html>  
See Live Example