where to store global data in angular JS? - javascript

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.

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();
}]);

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.

Related

How to share data among the controllers using $broadcast, $on and $emit?

I am new to AngularJS web development.
STEP 1. During initialization, I get login information from a server with http call. Say, UserName, UserID and some other information.
STEP 2. After successful http call, I would like to populate the loginObj object such as
$scope.loginObj = { UserID = '', UserName = '', SomeData: '' };
$scope.loginObj.UserID = 1000;
$scope.loginObj.UserName = 'John Doe';
$scope.loginObj.SomeData = 'Some other data';
STEP 3. I would like to broadcast $scope.loginObj object information with
$rootScope.broadcast method.
All the examples I have seen used some kind of click button. No Button Click
solution.
STEP 4. In the child controller, I would like to receive the broadcasted
information from the Parent Controller.
How can I receive this information?
STEP 5. Some times I get some extra information at the Child Controller as well.
How can I receive this information from Child controller to the Parent
Controller?
Please provide me a solution or direct me some sites where I can get the example.
Instead of using broadcast, create an angularjs service in which you persist the login info you got from http call and you can inject this service in the controller in which you need login info.
create a service like this :
/*app is your angular module name*/
app.factory('authFactory',['$state',function( $state){
var authFactory = {
currentUser: {},
setCurrentUser: function(userinfo){
authFactory.currentUser = userinfo;
},
getCurrentUser: function(){
return authFactory.currentUser;
}
};
return authFactory;
}
in your login controller, inject authFactory, then once user is logged in, call authFactory.setCurrentUser and pass an object ({login: userlogin, email: useremail}). if you need the logged in user in another page, just inject authFactory in that page and call authFactory.getCurrentUser().

How to Cache Angular scope

What is the best technique to cache Angular Scope from last browser session to a newly loaded one?
Is that possible?
Including to control the next time to create a cache of the complete scope?
And override the loaded cached scope, when new data is loaded from the back-end?
This is more related to how to cache data in the browser using javascript.
There are some solutions you can look into for angular specifically:
ngStorage: Local and session storage the angular way
angular-local-storage: Simple local storage with a cookies fallback
$cookies: Angular provided service wrapping cookies access
Angular services can be used to share the scope between routes within the same session. But if you close the browser, you'll need one of local/session storage, cookies, or a server-side solution.
$cookies
Cookies is a straightforward key-value storage. Easy to use for a quick way to save data.
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
}]);
Don't use cookies to store extensive data and limit this to data which should be sent on every request, like a authentication token.
ngStorage
An AngularJS module that makes Web Storage working in the Angular Way.
Contains two services: $localStorage and $sessionStorage.
bower install ngstorage
Pass $localStorage (or $sessionStorage) by reference to a hook
under $scope in plain ol' JavaScript:
$scope.$storage = $localStorage;
And use it like you-already-know:
<body ng-controller="Ctrl">
<button ng-click="$storage.counter = $storage.counter + 1">{{$storage.counter}}</button>
</body>
Optionally, specify default values using the $default() method:
$scope.$storage = $localStorage.$default({
counter: 42
});
With this setup, changes will be automatically sync'd between
$scope.$storage, $localStorage, and localStorage - even across
different browser tabs!
local storage demo
The angular-local-storage module provides multiple ways to store your data. It's feature rich and provides advanced options and customisation.
window.angular.module('demoModule', ['LocalStorageModule'])
.config(function(localStorageServiceProvider) {
localStorageServiceProvider.setPrefix('demoPrefix');
// localStorageServiceProvider.setStorageCookieDomain('example.com');
// localStorageServiceProvider.setStorageType('sessionStorage');
})
.controller('DemoCtrl',
function($scope, localStorageService) {
$scope.localStorageDemo = localStorageService.get('localStorageDemo');
$scope.$watch('localStorageDemo', function(value) {
localStorageService.set('localStorageDemo', value);
$scope.localStorageDemoValue = localStorageService.get('localStorageDemo');
});
$scope.storageType = 'Local storage';
if (localStorageService.getStorageType().indexOf('session') >= 0) {
$scope.storageType = 'Session storage';
}
if (!localStorageService.isSupported) {
$scope.storageType = 'Cookie';
}
$scope.$watch(function() {
return localStorageService.get('localStorageDemo');
}, function(value) {
$scope.localStorageDemo = value;
});
$scope.clearAll = localStorageService.clearAll;
}
);
Additional information
How to access cookies in AngularJS
How to set expiration date for cookie in AngularJS
How to persist data in AngularJS

Passing id to json data in angular js

I am trying to create a chat application through angular and php.
I have created 2 controllers.
One is for displaying the number of peoples online and other controllers is for sending and recieving messages.
In MainController I can show the person name whom I clicked but in SendMessageController I don't know how to show the same person name.
Please help me, I'm new to angular.
here is working Plunker Link
Use service to share the data between controllers.
Inject the service to both controllers.
app.service('userService', function() {
this.userId = '';
this.setUserId = function(id) {
this.userId = id;
};
this.getUserId = function() {
return this.userId;
};
}
Full example

Reloading a page in angularjs application looses data

Background:
I have a multi page angularjs application. I have a service factory object that I load with values in my initial page. The values loaded to the service factory object are available in the different views or pages via their corresponding controller js. The value provided by the user is lost if the user tries to do a browser refresh by clicking F5 button.
My issue:
When the application is loaded the 'loginView' is displayed, the userId and password entered by the user is passed to the second view (summaryView.html). And i can see the userId and password displayed correct in the second page. But if i refresh my second view (summaryView.html) then I loose all the values. The application is sort of reset.
I would like to retain the user supplied data even after the browser is refreshed or reloaded.
My code:
**index.html**
<div ng-app="offlineInspectionApp">
<div ng-view></div>
</div>
<script>
var mainApp = angular.module("offlineInspectionApp", ['ngRoute']);
mainApp.factory( 'AuthService', function() {
var userCore = {userId : "anonymous" , password: "password", status :"online"};
return {userCore: function() { return userCore; }};
});
mainApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/summary', {
templateUrl: 'summaryView.html',
controller: 'SummaryViewController'
}).
when('/login', {
templateUrl: 'loginView.html',
controller: 'LoginViewController'
});
}]);
**LoginViewController.js**
angular.module("offlineInspectionApp").controller('LoginViewController', function($scope,$http,$location, AuthService) {
$scope.authenticateUser = function() {
AuthService.userCore.userId = $scope.userId;
AuthService.userCore.password = $scope.password;
$location.path( "/summary" );
}
});
**SummaryViewController.js**
angular.module("offlineInspectionApp").controller('SummaryViewController', function($scope,$http,$location, AuthService) {
$scope.syncInspectionDetails = function(inspectionId) {
alert(AuthService.userCore.userId +' '+ AuthService.userCore.password);
};
I have two html files 'loginView.html' and 'summaryView.html'
Flow
1- when the user enter the correct username and password you store the data in angular variables. this is fine and it redirect to summary page. AuthService.userCore has the same scope over the summery page so it displays the details on first attempt.
2- when you refresh the page all the variable you declared in angularJs are cleared. So when you refresh the page you didn't get those variables.
Solution
there are two ways
1- either store the whole user data in cookie, and fetch the data from cookie on refresh.
2- one sign in complition use any access token and store it in cookie. And check for the access token and fetch the data from backend again on every refresh.

Swapping Handlebars for Angular in MEAN app

I'm building a MEAN app with user authentication and I'm currently in the process of learning Angular (I like to learn by using whatever it is I'm learning in a practical way). Anyway, before I stripped the handlebars view engine and changed the view files from .hbs to .html I was able to display the username of the currently authenticated user like so:
Handlebars: {{user.username}} = req.user.username and it displays the username of the current authenticated user.
Rather than using render for rendering my pages, I'm now using sendfile:
app.get('/dashboard', Auth.ensureAuthenticated, function (req, res) {
res.sendfile('./app/views/admin.html', req);
});
I'd like to know how I go about rendering the username of the currently authenticated user in Angular.
You can send the user info by
Setting a global variable using your handlebar template.
app.get('/dashboard', Auth.ensureAuthenticated, function (req, res) {
res.render('admin',{user: user});
});
And in handlebar template add something like below
<script type="text/javascript">
window.user = {{user}};
</script>
wrap this global in angular service
angular.module('myApp').service('Global', ['$window', function($window){
function _getUser() {
return $window.user;
}
return {
user: _getUser()
};
}]);
Now in your controller, you can access the user data by injecting Global service
angular.module('myApp').controller('AdminController', ['$scope', 'Global', function($scope, Global) {
$scope.user = Global.user;
}])
User will be available in your angular partial views.
<div data-ng-controller="AdminController">
Welcome <span ng-bind="user"></span>
</div>
or you can send the information via cookie. After reading the cookie value inside _getUser function in angular service, delete the cookie.
or you can send an ajax request for fetching the data inside angular service.

Categories