简体   繁体   English

Angularjs在另一个文件中调用函数

[英]Angularjs calling function in another file

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? 我的问题很像这样: AngularJS种子:把JavaScript放到单独的文件中(app.js,controllers.js,directives.js,filters.js,services.js)我可以在其中一个文件中创建一个函数被另一个人打电话? 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! 任何帮助都会很棒!

Accessing another controller would be completely wrong. 访问另一个控制器是完全错误的。 You have a lot of ways to communicate between them. 你有很多方法可以在他们之间进行交流。 Here are 3 easy ones: 这里有3个简单的:

  1. 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). 范围:您可以使用$ parent或简单地使用$ rootScope访问所有父控制器的范围(不要过度使用它,否则您的根范围将是混乱的)。 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. 在范围变量上使用$ watch可以在需要时使代码更清晰。 (see the scope documentation) (参见范围文档)

  2. 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). 你用$ scope。$ on听,你用$ scope发送它。$ broadcast或$ scope。$ emit(取决于你是否想要通知孩子或父母)。

  3. 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. 如果有什么不清楚,请告诉我。

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

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