简体   繁体   中英

AngularJs defining global variables

What is the best way to define a global varible in AngularJS ?

I know there are plenty of solutions about this topic, the most commom:

  • Use a service;
  • Use $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 ;
  • The name of a main module: myApp ;
  • A commom alert message for an error: 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 :

  • Use AngularJS constants ;
  • Use JS var outside of the main ng module;

So my question is: For the AngularJs scenario, what is the best alternative?

Do we really use constants for this situation? 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. If your values may need to be configured or calculated use an Angular service and expose getter functions. For strings you may want to consider localization, so use one of the Angular localization libraries to store these (I use Angular-localize).

Hope this is helpful.

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