简体   繁体   English

定义全局变量的AngularJ

[英]AngularJs defining global variables

What is the best way to define a global varible in AngularJS ? AngularJS定义全局变量的最佳方法是什么?

I know there are plenty of solutions about this topic, the most commom: 我知道有很多关于此主题的解决方案,这是最常见的:

  • Use a service; 使用服务;
  • Use $rootScope; 使用$ rootScope;

I want an answer for a different context. 我想要一个针对不同背景的答案。 For example: 例如:

  • A commom url used for multiple requests in multiple services: my/folder/class.php ; 一个用于多个服务中的多个请求的公共URL: my/folder/class.php
  • The name of a main module: myApp ; 主要模块的名称: myApp ;
  • A commom alert message for an error: Failed to connect to the server, try again. 出现错误的公共警报消息: Failed to connect to the server, try again.

Things that will be used all over the app, in different situations and will never change. 在不同情况下将在整个应用程序中使用且不会改变的事物。


Looking around the internet I saw 2 other possibilities other then $rootScope and services : 环顾互联网,我看到了除$rootScopeservices以外的其他两种可能性:

  • Use AngularJS constants ; 使用AngularJS constants ;
  • Use JS var outside of the main ng module; 在主要ng模块之外使用JS var

So my question is: For the AngularJs scenario, what is the best alternative? 所以我的问题是:对于AngularJs场景,最佳选择是什么?

Do we really use constants for this situation? 在这种情况下,我们真的使用constants吗? Is there any other provider for this purpose. 是否有其他提供者用于此目的。 Also I'd like to know whats the performance impact of the, if any. 我也想知道它对性能的影响,如果有的话。

For true constants use Angular constants. 对于真实常量,请使用Angular常量。 If your values may need to be configured or calculated use an Angular service and expose getter functions. 如果您的值可能需要配置或计算,请使用Angular服务并公开getter函数。 For strings you may want to consider localization, so use one of the Angular localization libraries to store these (I use Angular-localize). 对于字符串,您可能需要考虑本地化,因此请使用Angular本地化库之一来存储它们(我使用Angular-localize)。

Hope this is helpful. 希望这会有所帮助。

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

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