This question already has an answer here:
I need to call function in another controller in angular js.How it is possible way please help me thanks in advance
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
}
}
]);
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:
While
$rootScope.$emit
is called, you can send any data as second parameter.You may use events to provide your data. Code like that:
If the
two
controller is nested inOne
controller.Then you can simply call:
Angular will search for
parentmethod
function starting with current scope and up until it will reach therootScope
.I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.
The best approach for you to communicate between the two controllers is to use events.
See the scope documentation
In this check out
$on
,$broadcast
and$emit
.If you would like to execute the parent controller's parentmethod function inside a child controller, call it:
You can try it over here