1

What is the best way to store a "user" object that is accessible across all controllers in an Angular application?

I also have a function that fetches & sets the user.

Option 1: $rootScope

At first I was just setting $rootScope.user = myUser. Then in every control I could use $rootScope. This was fine, until I ended up with a lot of duplicate code since I had to check if it existed at the start of each controller.

// At the start of each controller

if (!$rootScope.user) {
  // fetch and set user
} 

Option 2: Angular service?

Option 3: Angular factory?

References: angular.service vs angular.factory

Community
  • 1
  • 1
Don P
  • 60,113
  • 114
  • 300
  • 432
  • Missing a fundamental part of $scope inheritance. If it's on $rootScope...$scope in controller will already inherit that property [ultra simple demo](http://plnkr.co/edit/4TfpZzSaACDD2odFCA3s). In other words when you were injecting it and adding it to $scope...it was already there and available. I'm not saying this is how it should be done...more just pointing it out. – charlietfl Jul 24 '15 at 23:43
  • Thanks @charlietfl - I understand that part :) But since a person can open the app on many different controllers, I always need the check. – Don P Jul 24 '15 at 23:49
  • 1
    back to the question...if using UI router can add a resolve to abstract state that is parent of all states that require auth. Then you only need a check one place for many routes. Just wire it up to your Auth service – charlietfl Jul 24 '15 at 23:54
  • That's a really interesting solution. Let me look into that. – Don P Jul 25 '15 at 00:07

2 Answers2

0

I would use a factory over a service, or $rootScope.

As Ed pointed out below, both a service and a factory are singletons.

$rootScope, as the name implies is the root of all scopes in an angularjs application.

Here is something for reference: http://ilikekillnerds.com/2014/12/angularjs-service-vs-factory/

Elan Hasson
  • 1,214
  • 1
  • 19
  • 29
  • This is incorrect. A factory also returns a singleton. Services and factories are very similar but are declared with a slightly different syntax. – Ed_ Jul 25 '15 at 00:13
  • Your are correct, I swapped em accidentally. Corrected above. – Elan Hasson Jul 25 '15 at 00:18
  • 1
    Still wrong ;) service creates a new instance once, but returns that same instance subsequently. – Ed_ Jul 25 '15 at 00:20
0

If you are creating a SPA and not creating a scope without parent then use rootScope it will work like a charm.

Utku Apaydin
  • 162
  • 1
  • 4