I am refactoring an AngularJS application, and there, almost everything is stored in the $rootScope
.
In my old applications I've build with Angular, I created a Service for each model, and then instantiated it within a Controller when needed.
I ask myself: Is it ok to store the whole user object inside the $rootScope or what is best practice here?
How can I get sure to create a user during login and then pass it around throughout the whole application?
It seems ok generally storing user like models in $rootScope. But In my opinion it's not a best practise in angularjs(However I have used $rootScope way before).
Factory is the one of angularjs' beauty. Generally we use it to call rest services. But also you can create a model with it. Also you will be able to extend your model easily with injecting another model. That's just an idea , may be there is another better options to use model like objects in angularjs.
Lets look an example
// User Model
app.factory('User', function() {
var User = function(username) {
this.username = username;
this.email = null;
};
User.prototype.getDetails = function() {
var self = this;
return self.username;
};
return User;
});
// ExtendedUser Model
app.factory('ExtendedUser', function(User) {
var ExtendedUser = function() {
User.apply(this, arguments);
};
ExtendedUser.prototype = new User();
function getEmail() {
var self = this;
// You can make an http call to get email like information as an extra
self.email = "email@email.com";
return self;
}
ExtendedUser.prototype.getDetails = function() {
var self = this;
var extendedUser = getEmail();
return extendedUser;
};
return ExtendedUser;
});