Bhimisetty
Bhimisetty

Reputation: 236

Call one controller function in another controller

Is there any possibility to call one controller function in another controller. I have been seeing that the data is manipulating in between controllers, but not the functions.

For Example. I have two controllers.

Module.Controller('Controller1', function($scope){
    $scope.function1 = function(){};
});

Module.Controller("Controller2", function(){
    // I need to call the function function1() from the controller1
});

Is this possible? Can you help me to solve this.

Upvotes: 0

Views: 178

Answers (2)

thomaux
thomaux

Reputation: 19708

If you need to reuse logic from another controller, I would suggest moving that logic to a service that you can inject in both controllers. This is a much cleaner solution and is easier testable.

Example:

Module.service("Service1", function(){
    this.function1 = function(){
        ...
    }
});

Module.Controller('Controller1', function($scope, Service1){
    $scope.function1 = Service1.function1;
});

Module.Controller("Controller2", function(Service1){
    // I need to call the function function1() from the controller1
    // simply call Service1.function1 here
});

Upvotes: 3

Michael
Michael

Reputation: 3326

You have cannot call one function into another controller directly. But, you can change the thing in the following ways:

  1. Use $rootScope.function1 instead of $scope, $rootScope is available from every $scope
  2. Use $rootScope.$emit to call an event from Controller2 and catch it with $rootScope.$on in Controller1 and then use the function
  3. You can define the function in a Service and use it from both controllers
  4. You can use a $scope.$watch or $rootScope.$watch if the controller 2 can change some variable in the Controller1 scope, or use $rootScope.$watch unless

Upvotes: 0

Related Questions