When I try to call one controller method from another controller in the angular javascript, an error occurs. I think something is missing there. If anyone has the plete method to do this, please give me the answer.
When I try to call one controller method from another controller in the angular javascript, an error occurs. I think something is missing there. If anyone has the plete method to do this, please give me the answer.
Being able to share a variables throught different controllers it's a mon issue in angular.
Your function can be seen as an object: you'll need to share it's reference throught scopes.
To perform that, you can either:
.
You can see services as singletons object that are injected in your controllers: a mon object shared throught your controllers.
You can use this wonderful guide to understand how to share your scope variables by using services (this guide uses factory and not services, but for your needs will be ok).
If you still wants to use services, follow this answer.
.
Sometimes you have a hierarchy between controllers (and thus, scopes). Let's assume you have an HTML formatted this way:
<div ng-controller="parentController">
<!-- some content here...-->
<div ng-controller="childController">
<!-- some content here...-->
</div>
</div>
This structure will produces two different scopes: one for parentController, and one for childController. So, you childController scope will be able to access parentController scope by simply using $parent object. For example:
myApp.controller('parentController', function($scope) {
$scope.functionExample = function(){
console.log('hey there');
};
})
myApp.controller('childController', function($scope) {
$scope.functionExample();
});
Note: the parent object is accesible directly in your child scope, even if declared in your parent.
But beware of this method: you can't never really sure of your scope hierarchy, so a check if the variable is defined should be always needed.
.
You can use rootscope as a mon shared object to share yours. But beware: this way, you'll risk to pollute your $rootScope of variables when $rootScope should be used for other uses (see message broadcasting).
Anyway, see this answer for an example use case.
.
By using messages, you can share objects references, as shown in this example:
myApp.controller('parentController', function($scope, $rootScope) {
var object = { test: 'test'}
$rootScope.$broadcast('message', message)
console.log('broadcasting');
});
myApp.controller('childController', function($scope, $rootScope) {
$scope.$on('message', function(message){
console.log(message);
});
});
.
In the end, i suggest you to use a mon service for all your variables or, where you can, use the scope hierarchy method.
If two controllers are nested in one controller, then you can simply call the other by using:
$scope.parentMethod();
Angular will search for parentMethod()
function starting with the current scope up to it reach the $rootscope