Reputation: 236
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
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
Reputation: 3326
You have cannot call one function into another controller directly. But, you can change the thing in the following ways:
$rootScope.function1
instead of $scope
, $rootScope
is
available from every $scope
$rootScope.$emit
to call an event from Controller2 and catch it with $rootScope.$on
in Controller1 and then use the function$scope.$watch
or $rootScope.$watch
if the controller 2 can change some variable in the Controller1 scope, or use $rootScope.$watch
unlessUpvotes: 0