Skip to content
Loading
How to call controller function from another controller  
  •   
  • var app = angular.module('MyApp', []);  
  •   
  • app.controller('Ctrl1', function($scope,$rootScope) {  
  •   
  •   $scope.func1 = function() {  
  •     alert('Ctrl1 and func1')  
  •   }  
  •   
  •     $rootScope.$on("MyFunction", function () {  
  •         alert('Ctrl1 MyFunction')  
  •     });  
  • });  
  •   
  • app.controller('Ctrl2', function($scope) {  
  •   
  •   $scope.func2 = function() {  
  •     alert('Ctrl2 and func2')  
  •     $scope.$emit("MyFunction");  
  •   }  
  •   
  • }); 
  •  2nd approach
    1. app.controller('Ctrl1', function($scope) {  
    2.   
    3.   $scope.func1 = function() {  
    4.     alert('Ctrl1 and func1')  
    5.   }  
    6.   
    7.     $scope.$on("MyFunction", function () {  
    8.         alert('Ctrl1 MyFunction')  
    9.     });  
    10. });  
    11.   
    12. app.controller('Ctrl2', function($scope, $rootScope) {  
    13.   
    14.   $scope.func2 = function() {  
    15.     alert('Ctrl2 and func2')  
    16.     //$scope.$emit("MyFunction");  
    17.     //USE rootScope  
    18.     $rootScope.$broadcast("MyFunction");  
    19.   }  
    20.   
    21. }); 
     thanks
  • @Thiruppathi thanks for your reply.
     
    i try to follow your code but it is not working. here is the code what i tried and failed. please see and tell me why the code is not working.
     
    1. "MyApp">  
    2.     "Ctrl1">  
    3.         "func1()">func1  
    4.     
      
  •     
      
  •     "Ctrl2">  
  •         "func2()">func2  
  •       
  •   
  •   
  • var app = angular.module('MyApp', []);  
  •   
  • app.controller('Ctrl1', function($scope) {  
  •     
  •   $scope.func1 = function() {  
  •     alert('Ctrl1 and func1')  
  •   }  
  •     
  •     $scope.$on("MyFunction", function () {  
  •         alert('Ctrl1 MyFunction')  
  •     });  
  • });  
  •   
  • app.controller('Ctrl2', function($scope) {  
  •     
  •   $scope.func2 = function() {  
  •     alert('Ctrl2 and func2')  
  •     scope.$emit("MyFunction");  
  •   }  
  •   
  • }); 
  •  
  • Thiruppathi R
    Ya,We can call. follow the below code
     
    Controller  1:
     
    $scope.$on("MyFunction", function (event, args) {
     
     
    Controller 2: 
     
     scope.$emit("MyFunction", { file: files[i] });
     
    even you can call Ctrl 1 function  from directives & factory using $emit. 
  • i post the question in angular setcion not in asp.net mvc area.
     
    before answer try to read question properly.
  • Manas Mohapatra
    You can try like below: 
    1. public ActionResult FirstAction()  
    2. {  
    3.    OtherController c = new OtherController ();  
    4.    ActionResult result = c.SomeMethod();  
    5.   
    6.    return View();  
    7. }