Angular Scope

One of my early misunderstandings with Angular was around scope. Scope provides a means for a controller and a view to communicate. The controller sets a variable on the scope and the view binds to it. Change the value of the variable and the view is updated – simple.

Of course having a single global scope that everyone has access to is a bad idea.


Rather than a single global scope each controller gets its own scope that is a child of the parent scope (the parent scope can still be accessed through the rootScope if needed). Still pretty simple.

My misunderstanding came when I had an authentication controller. The controller let you login and check your auth status and I used it twice. Once as the basis of the login and then again in the nav to toggle the login/logout link based on the users status. The simple mistake I made was in thinking that the controller “owned” the scope.


I had a variable that was bound to the logged in status on the scope. It refused to update when the status was changed by the (separate controller instance) log in. If the controller owned the scope then that should have worked. Unfortunately for me I assumed I had a bug rather than a fundamental understanding of how scope worked.

After a fair amount of Googling I came up with a new approach. I finally got it into my skull that I was dealing with different instances of the scope and the Internet said to use a broadcast to communicate between controllers…


That didn’t seem to work either…in my particular case I was using the same controller twice which seemed to defeat the broadcast (I never truly got to the bottom of this so who knows if that was my error or just not possible).

After a bit more research I realised I had two options.
a) create a separate controller and then use broadcast
b) use a shared service to hold the state


My preference was to create a separate service to encapsulate the authentication logic and state – after all, trying to do this in the controller was probably a design smell and if I’d been less lazy I wouldn’t have done it in the first place.
Turned out that a bit of thought initially would have avoided a lot of pain…but I would also have missed out on a deeper understanding of Angular’s scope concept.