简体   繁体   English

在另一个angularjs中使用控制器的功能

[英]Use function of a controller in another angularjs

Few days I've been trying to solve it using a function of a controller in another. 几天我一直在尝试使用另一个控制器的功能来解决它​​。

I have to get is that when you press a button click go away to another part of the application but with an open form. 我必须得到的是,当您按下按钮时,请单击该应用程序的另一部分,但使用打开的表单。 I have a function that opens the form in your controller working perfectly but I need to invoke that function from another part of the application for this (or it might please him happens to someone other way). 我有一个函数可以在你的控制器中打开表单,但是我需要从应用程序的另一部分调用该函数(或者它可能会让其他人感到高兴)。

I hope you can help me I do not know what else to give ... 我希望你能帮助我,我不知道还有什么可以给...

Greetings and thanks. 问候和感谢。

Move the function inside a factory. 在工厂内移动功能。 You can inject this factory in any controller to access the function. 您可以在任何控制器中注入此工厂以访问该功能。

controller('controller1', function(sharedFunctions){
   sharedFunctions.function1();
})

controller('controller2', function(sharedFunctions){
   sharedFunctions.function1();
})

factory('sharedFunctions', function(){

   return {
      function1: function() {
         console.log('function1 called')' 
      }    
   }
})

Bad answer: you can do this if the scope of your controller is child of the other controller (the one with the function to call). 答案不好:如果控制器的范围是另一个控制器(具有要调用的功能的控制器)的子控件,则可以执行此操作。 I believe this is not your case. 我相信这不是你的情况。

Better answer: you should move this function to a service, so that you can reuse it and call it from anyother place of your application. 更好的答案:您应该将此功能移至服务中,以便您可以重复使用它并从应用程序的任何其他位置调用它。 If the function is well written (loose coupled) it should be easy to do this. 如果函数写得很好(松散耦合),那么应该很容易。

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

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