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 } } ]);
If the two controller is nested in One controller. Then you can simply call: $scope. parentmethod();
You can't inject controllers into one another.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With