development

JS Quickie: AngularJS Global Values

by Jamal on August 17, 2015

Back with a quick code snippet in JavaScript. To be more specific, AngularJS!

Now for those new to Angular, you probably don’t have the best setup in place in your project to handle this properly. Honestly, it took me a couple first run projects until I started thinking and realizing the way I was doing it wasn’t the best route. But that’s enough of living in my past mistakes, let’s move onto the actual solution!

The Situation

 

Now the core of AngularJS is three major components: App.js file, Index.html, and your Controllers. Essentially with these three, or just the first two depending on your needs, you could have a fully functioning SPA(Single Page Application) to show off to your friends or brag to your boss.

Now at first, when coming up on the idea of of globally accessible values the first thing that pops up is $rootScope! This is a great idea to many beginners because its already presently available at every component level, so why not use it?

The way I see it, $rootScope is a great place to store application globals that may not be associated with application status, any errors, or other information on that level. For user data, I prefer to use a service. I like to use a service because it has the same access level of $rootScope, and is only there when needed.

Consider an actual large SPA you are building. In this sense, you will be using a lot of data and a lot of information that probably will need to be shared between different application states. That creates a question of what type of information needs to be readily accessible across all states? And then, it also brings the question of at what level of importance?

That is why the separation of service level and $rootScope level data is important. We’ll be going into a deeper discussion about this later, so any questions here shall be answered.

Now without further wait, here is the global values service.