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
}
}
]);
This question is related to
angularjs
controller
angularjs-scope
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.
You may use events to provide your data. Code like that:
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) {
...
});
}]);
If the two
controller is nested in One
controller.
Then you can simply call:
$scope.parentmethod();
Angular will search for parentmethod
function starting with current scope and up until it will reach the rootScope
.
If you would like to execute the parent controller's parentmethod function inside a child controller, call it:
$scope.$parent.parentmethod();
You can try it over here
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
.
Source: Stackoverflow.com