0

From what I've read, one would generally use a global variable so that all controllers have access to some data.

Is there an "best-practice" way of accessing global data in the view templates? The use case would be for storing semi-static data like the website's brandname or location address. If in the future that data changes (ie, rebranding), it would be trivial to update the view to reflect those changes.

This thread suggests that using $rootScope is bad, and a better way would be to use a Service. However, in my case this gets messy because I have to mentally remember to include the service and create a scope var in each controller that has a template that will reference the static data.

I've seen suggestions of storing this data in a database, and then querying for it when needed. But that advice tends to be for server-side frameworks, and I would rather not do a GET query to the server just to grab static data in Angular.

I could leave it hardcoded as I have it now, and just run a grep to search and update whatever templates.

Is there a way to assign static data to variables once, and then have it be accessed in the templates without going through hoops? And all the while following Angular best practices? Or perhaps hardcoding the the easiest/cleanest approach?

rublex
  • 1,893
  • 5
  • 27
  • 45

1 Answers1

0

Service Factory behave like singleton, when injected in different module you actually access the same data so it works perfectly for communication between controller.

Each component dependent on a service gets a reference to the single instance generated by the service factory.

If you want access those data in your template, just include the object in your scope, display. This will automatically implement two-way binding and is a good practice for MVC pattern.

To know the difference between Service and Factory : angular.service vs angular.factory

But try to avoid as much as possible to use global variable :D

BUT

This apply in a perfect world with perfect developer ... I love using a global variable like SETTINGS (uppercase to make it sounds constant) and which include some data required before angular initialization for exemple.

Would work well for such data like title and stuff like you have. However, you still need to add it manually in your scope (which for a title would be ... once ? Yeah seems ok)

Community
  • 1
  • 1
sebastienbarbier
  • 6,542
  • 3
  • 29
  • 55