Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it ok to store an object on $rootScope in AngularJS

Tags:

angularjs

I see many tutorials on authentication that put an 'auth' object on $rootScope, including the AngularFire-seed from the FireBase-people.

I thought it was bad practice to put objects on the rootscope and one should rather create a service instead. Why is this (apparently) ok when it comes to authentication? Or rather the more general question: When is it ok and perhaps even good practice to put something on the rootscope?

To give another example. I have in addition a profile-object on the user. Is it also ok to add this to the auth-object? I even do not pollute the rootscope in this case, since the auth-object is already there. Is it ok to put the profile on the rootscope like this (via the auth-object)? If not, why?

I know, it was several questions, but they all boil down to one the qeustion in the title...

like image 628
EricC Avatar asked Apr 11 '14 17:04

EricC


1 Answers

Most likely because of the way prototypical inheritance works in JavaScript.

For example: client would need auth credentials all across the app, what is a better place than $rootScope? (except if you want it in a service and inject that service all across artifacts). This works like an ASPECT to address a cross cutting functionality of carrying auth data. By adding auth related data in $rootScope, you can easily get auth detail from any scope which apparently inherits from $rootScope (due to prototypical inheritance).

This holds good for directives not with isolated scope, but for isolated scope as well the wall to climb will be small since you get the effective 2-way binding mechanism.

like image 82
dmahapatro Avatar answered Sep 29 '22 12:09

dmahapatro