Reputation: 273
What is the simplest way to call a controller's functions from another controller?
I have controller like this..
Controller1
$scope.setTitleKey = function (titleKey) {
$scope.currentTitleKey = titleKey;
$scope.getDetails();
};
Controller2
$scope.getDetails= function () {
if (titleKey !== "All") {
$scope.bookInfo;
bookDetails.getBookDetails(titleKey).then(function (results) {
$scope.bookInfo = results.data;
}, function (error) {
alert(error.data.message);
}
);
};
};
I just want to call function from other controller
The simple logic is that if the function from Controller1 then the another function is call from the Controller2
Any Idea?
Upvotes: 1
Views: 173
Reputation: 10378
make a factory or service when you want to share code in your controller
it is the best way to get all the function and variable which you want to share like
Modulename.factory("ABC",function(){// Modulename which you have make on your code it is just for a example
var test=0;
return {
/** by this get test var**/
"getABC":function(){
return test;
},
/**to set new new test value
* **/
"setABC":function(passtest){
test=passtest;
}
};
});
Now use in Controller 1
$scope.setTitleKey = function (titleKey,ABC) {
ABC.getABC();//get 0;
ABC.setABC(5);
};
Now use in Controller 2
$scope.getDetails= function () {
ABC.getABC();// get 5
};
Here i am sharing a logic which you can implement and for more search in angular doc it will helpful
Thanks
Upvotes: 1
Reputation: 2620
Short answer is that don't even try to communicate between controllers, instead use one of the communications patterns
$emit()
, $on()
and $broadcast()
As mentioned in the comments, these options in the in the order of best practices.
Upvotes: 3