My question is a lot like this: AngularJS seed: putting JavaScript into separate files (app.js, controllers.js, directives.js, filters.js, services.js) Just can I make a function in one of the files that can be called by another? And if so what do I have to add? The only reason I'm not adding to it is because it is closed. Any help would be great!
-
What are you adding to? The controller, service, or directive. And are you able to include the new JS file into the code if it is locked? – tymeJV Aug 27 '13 at 00:05
-
@tymeJV I was just giving an example of what kind of template I'm using to make it easier to understand what I am trying to do. Pretend they are all controllers. ***I want one controller to call a function in another controller in another file.*** – alex wilhelm Aug 27 '13 at 00:15
-
@alexwilhelm if you are trying to have controllers "talk" to one another a simple way is to create a service and inject them into the controllers so you can have methods defined in the service and then the controller(s) can call to them when they are injected – David Chase Aug 27 '13 at 02:02
1 Answers
Accessing another controller would be completely wrong. You have a lot of ways to communicate between them. Here are 3 easy ones:
Scope: you can access the scope of all your parent controller using $parent or simply the $rootScope (don't overuse it or your root scope will be clutter). Remember that your scope always have your parent scope objects too until you change them. Using $watch on a scope variable can make you code cleaner when needed. (see the scope documentation)
Event: Pretty straightforward. You listen with $scope.$on and you send it with $scope.$broadcast or $scope.$emit (depending if you want the notice the children or the parents).
Service: if what you are trying to implement has no clear controller owner, you might have to consider using a service. Then, you can use it within all your controllers. (See Creating Services)
Most of the time, you will end up using the scope because you want to interact with your parent controller. Let me know if anything is unclear.

- 3,125
- 1
- 23
- 35

- 698
- 5
- 17