1

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?

2 Answers 2

3

Short answer is that don't even try to communicate between controllers, instead use one of the communications patterns

  1. Using a shared service (PREFERRED).
  2. Using events $emit(), $on() and $broadcast()
  3. Use scope inheritance.

As mentioned in the comments, these options in the in the order of best practices.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for shared service... +0.5 for events -1 for scope inheritance.
1

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

1 Comment

Thanks a lot.. and thanks for the example guide for me.. i got it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.