Archive

Posts Tagged ‘on’

Angular JS: Calling one controller from another controller

February 20, 2017 Leave a comment

Hi friends,

I came across a requirement where I am having multiple controllers referred on my page and I wanted to call one controller method from another controller.

This is common sacnorao while dealing with multiple controllers.

Problem statement:

Calling one controller method from another controller.

Solution:

We need to use ‘$emit’ and ‘$on’ services for event based communication and expose the function to other controller on $rootScope.

Following code explains how we can achieve this.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.js">
</script>
<script>
var myApp = angular.module('MyTest', []);
myApp.controller('My1Controller', function($scope,$rootScope) {
  $scope.childmethod = function() {
            $rootScope.$emit("CallMy2ControllerMethod", {message: 'in My Controller 2'});
        }
		
		$scope.childmethod2 = function() {
            $rootScope.$emit("CallMy3ControllerMethod", {message: 'in My Controller 3'});
        }
});
myApp.controller('My2Controller', function($scope,$rootScope) {
   $rootScope.$on("CallMy2ControllerMethod", function(event,param1){
           $scope.My2ControllerMethod(param1);
        });

        $scope.My2ControllerMethod = function(param1) {
			alert(param1.message);
        }
});
myApp.controller('My3Controller', function($scope,$rootScope) {
  $rootScope.$on("CallMy3ControllerMethod", function(event,param1){
           $scope.My3ControllerMethod(param1);
        });

        $scope.My3ControllerMethod = function(param1) {
			alert(param1.message);
        }
});
</script>
</head>
<body ng-app="MyTest">
<div ng-controller="My1Controller">
This is "Controller 1"
 <input type="button" value="Call My2Controller" ng-click="childmethod()">

 <input type="button" value="Call My3Controller" ng-click="childmethod2()"></div>
<div ng-controller="My2Controller"></div>
<div ng-controller="My3Controller"></div>
</body>
</html>

In above example we are calling My2Controller and My3Controller methods from My1Controller.

We have made method ‘CallMy2ControllerMethod’ and ‘CallMy3ControllerMethod’ available using ‘$on’ and we can call the method using $emit.

There is another way to use ‘$broadcast’ and ‘$on’ but it’s better to use ‘$emit’ and ‘$on’ as it destroys the listener.

Hope this will help some of the developers.

Advertisements