How to call a function from another controller in angularjs?

I need to call a function in another controller in angular js.Whenever this is possible, please help me in advance

The 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 } } ]); 
+47
angularjs angularjs-scope controller
Apr 6 '15 at 7:43
source share
6 answers

Communication between controllers is performed, although the methods are $emit + $on / $broadcast + $on .

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

 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 , you can send any data as a second parameter.

+97
Apr 6 '15 at 9:23
source share

I would not use a function from one controller to another. A better approach would be to move a common function into a service, and then deploy the service in both controllers.

+19
Apr 6 '15 at 7:50
source share

If the two controller is nested in the One controller.
Then you can just call:

 $scope.parentmethod(); 

Angular will search for the parentmethod function, starting from the current scope and until it reaches rootScope .

+8
Apr 6 '15 at 9:23
source share

You can use events to provide your data. Code like this:

 app.controller('One', ['$scope', function ($scope) { $scope.parentmethod=function(){ $scope.$emit('one', res);// res - your data } }]); app.controller('two', ['$scope', function ($scope) { $scope.$on('updateMiniBasket', function (event, data) { ... }); }]); 
+4
Apr 6 '15 at 7:47
source share

The best approach for communicating between two controllers is to use events.

See scope documentation

In this case, check $on , $broadcast and $emit .

+4
Apr 6 '15 at 7:50
source share

If you want to execute the parent method of the parent controller in the child controller, call it:

 $scope.$parent.parentmethod(); 

You can try it here

0
Apr 6 '15 at 8:44
source share



All Articles