简体   繁体   English

如何从另一个控制器调用一个控制器功能?

[英]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 控制器1

$scope.setTitleKey = function (titleKey) {
        $scope.currentTitleKey = titleKey;
        $scope.getDetails();
    };

Controller2 控制器2

$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 简单的逻辑是,如果从控制器1的功能,则另一个功能是从控制器2呼叫

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 ). 使用共享服务( PREFERRED )。
  2. Using events $emit() , $on() and $broadcast() 使用事件$emit()$on()$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 现在在控制器1中使用

$scope.setTitleKey = function (titleKey,ABC) {
  ABC.getABC();//get 0;
  ABC.setABC(5);

 };

Now use in Controller 2 现在在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 我在这里分享您可以实现的逻辑,如果要在angular doc中进行更多搜索,这将有所帮助

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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