简体   繁体   中英

How to call a controller function from another controller?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM