Accessing functions of one controller from another in angular js

There are many ways of calling a function from a controller  which is in another controller in Angular Js.

  1. $emit() or $broadcast()
  2. $controller
  3. Create a factory / service and inject them in controller.

One of the best ways of doing it is injecting $controller in your controller.This way we are sure about calling the function compared to $emit or $broadcast, as both would create a listener in the scope or rootScope level when they are initiated respectively.If they are not used in proper way you might not be able to call the function as it won’t register the listener .Generally in a scope hierarchy for above scopes we use $emit and for below we use $broadcast.

Below is a slight difference how we want to initiate the controller with and without creating new scope.

var secController= $scope.$new(); //creating a new scope..
$controller('secController',{$scope : secController });
$controller('secController',{$scope : $scope });//passing the current scope..

Following is the code snippet for accessing methods in another controller using  $emit, $broadcast and $controller.You can play with this Plunker Demo and watch them in action.

var mainApp = angular.module("mainApp", []);

mainApp.controller('MainCtrl',['$scope','$controller','$rootScope', function($scope,$controller,$rootScope) {

//using $controller..
$scope.navigateToList= function(){
    var secController= $scope.$new(); //creating a new scope..
    $controller('secController',{$scope : secController });
    secController.getResultList();
};
//using $broadcast...
$scope.doSearch = function(){
     //we can pass the objects as arguments..
    //scope level boradcast created..
    $scope.$broadcast ('callSearch',$scope.req);
  //$rootScope.$broadcast('callSearch',$scope.req); rootScope level..
};
$scope.$on('showResult',function(event, args){
     $scope.show(args); 
});
$scope.show = function(param){
     $scope.display = param;
};
}]);

mainApp.controller('secController',['$scope',function($scope) {
$scope.getResultList = function (){
   //Do something ... 
};
//listen to the broadcast and catch..
$scope.$on('callSearch',function(event, args){
    $scope.search(args); 
});
$scope.search = function(args){
    var data;
    //processing..
   $scope.result = data;//data from search..
   //using $emit..
   $scope.$emit('showResult',$scope.result);
}; 
}]);
Advertisements