1

In angular Js i am trying to store user data such as profile name that should exist in most of routes is it a good practice to store them in the $rootScope. IF not where should i store them.

MohamedAbbas
  • 1,149
  • 4
  • 15
  • 31
  • There are a few answers to this question here that may help: http://stackoverflow.com/questions/22707699/how-to-create-this-global-constant-to-be-shared-among-controllers-in-angularjs/22708212#22708212 – Lee Willis Aug 05 '14 at 09:12

2 Answers2

3

If you use a service it's everywhere available and if it should be persistent over page reloads and so on, then you can store the data in local storage or a cookie etc. and access it with your service on load.

angular.module('app')
  .factory('UserService', ['SessionService', function(SessionService) {
       SessionService.load();
       var user = SessionService.getUser();

       var service = {
           setUser: function(u){ user = u; },
           getUser: function(){ return user; }
       };
       return service;
   }])
   .controller('DemoCtrl', ['$scope', 'UserService', function($scope, UserService){
       $scope.user = UserService.getUser();
   }]);
Raphael Müller
  • 2,180
  • 2
  • 15
  • 20
  • i have a session service that contains that data and a cookie for handling refresh but i will need to inject that service in every view is that right way of doing it. – MohamedAbbas Aug 05 '14 at 09:07
  • Yes, you need to inject the service into every controller. – ABucin Aug 05 '14 at 09:10
0

I'm new to angular myself but the route I'm taking is to write a service. You could have a service that stores the user profile data. I would maybe put a method on the service to load the profile data and then store it locally in the service. You could then get this information via a getter method.

Ben Thurley
  • 6,943
  • 4
  • 31
  • 54
  • thanks for you help. That's what i had implemented, i am asking for a better way i heard about something called application controller that is being defined on the body tag – MohamedAbbas Aug 05 '14 at 09:15