简体   繁体   中英

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.

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