Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function from another controller in angularjs? [duplicate]

I need to call a function in another controller in AngularJS. How can I do this?

Code:

app.controller('One', ['$scope',     function($scope) {         $scope.parentmethod = function() {             // task         }     } ]);  app.controller('two', ['$scope',     function($scope) {         $scope.childmethod = function() {             // Here i want to call parentmethod of One controller         }     } ]); 
like image 379
Bhavesh Chauhan Avatar asked Apr 06 '15 07:04

Bhavesh Chauhan


People also ask

Can we call function from another controller in AngularJS?

If the two controller is nested in One controller. Then you can simply call: $scope. parentmethod();

Can we inject one controller into another controller in AngularJS?

You can't inject controllers into one another.

Can we have two controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application. This approach will make your code cleaner and easy to maintain and upgrade. Angular creates one $scope object for each controller.


1 Answers

Communication between controllers is done though $emit + $on / $broadcast + $on methods.

So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:

app.controller('One', ['$scope', '$rootScope'     function($scope) {         $rootScope.$on("CallParentMethod", function(){            $scope.parentmethod();         });          $scope.parentmethod = function() {             // task         }     } ]); app.controller('two', ['$scope', '$rootScope'     function($scope) {         $scope.childmethod = function() {             $rootScope.$emit("CallParentMethod", {});         }     } ]); 

While $rootScope.$emit is called, you can send any data as second parameter.

like image 195
Yashika Garg Avatar answered Sep 20 '22 22:09

Yashika Garg