Chapter 7. Other Concerns

In this chapter, we will take a look at some other useful features that are present in AngularJS, but weren’t covered at all or in depth in the chapters and examples so far.


Up to now, you have seen quite a few examples of the $location service in AngularJS. Most of them would have been fleeting glances—an access here, set there. In this section, we will dive into what exactly the $location service in AngularJS is for, and when you should and shouldn’t use it.

The $location service is a wrapper around the window.location that is present in any browser. So why would you want to use it instead of working directly with window.location?

Goodbye global state
window.location is a prime example of global state (actually, both window and document objects in the browser are prime examples). The minute you have global state in your application, testing, maintaining and working with it becomes a hassle (if not now, then definitely in the long run). The $location service hides this nastiness (what we call global state), and allows you to test the browser’s location details by injecting mocks during your unit tests.
window.location gives you total access to the contents of the browser location. That is, window.location gives you the string while $location gives you nice, jQuery-like setters and getters to work with it in a clean way.
AngularJS integration
If you use $location, you can use it however you want. But with window.location, you would have ...

Get AngularJS now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.