Pregunta

We are in the process of migrating our webapp to Angular.js. Traditionally, we created a global object named app and used it to store functions, variables, etc. that were used globally. For example, the active user's name and avatar might be stored in app.user.

With the transition to angular, app is no longer just an object, it is an angular app module. What is the correct way to store data globally like this in an Angular mindset? It could be completely different, that's fine. I just want to make sure we do it correctly.

I would do something as simple as app.global = {}; and use app.global around the site, but if the angular API ever changes to use a property named global, it would be a nightmare to fix.

¿Fue útil?

Solución

Angular is fairly allergic to global variables. I would recommend using a service (e.g. UserDataService) to hold this data and injecting it where it is needed (like in a controller).

Your service will be a singleton that can be accessed wherever it is injected.

Otros consejos

The correct way to do this would be to provide the value or function to angular's dependency injector via Module.value or Module.constant. See: http://docs.angularjs.org/api/angular.Module

Well, you can also set it in rootScope as:

var app = angular.module('appName'){
   //other codes removed
}); 

app.run(function ($rootScope) {
    $rootScope.globalVariable = 'hello'; //global variable
});

Now you can access the globalVariable

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top