Currently I am using a service to perform an action, namely
retrieve data from the server and then store the data on the server itself.
Instead of this, I want to put the data into local storage instead of storing it on the server. How do I do this?
this is a bit of my code that stores and retrieves to local storage. i use broadcast events to save and restore the values in the model.
app.factory('userService', ['$rootScope', function ($rootScope) {
var service = {
model: {
name: '',
email: ''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
}]);
If you use $window.localStorage.setItem(key,value) to store,$window.localStorage.getItem(key) to retrieve and $window.localStorage.removeItem(key) to remove, then you can access the values in any page.
You have to pass the $window service to the controller. Though in JavaScript, window object is available globally.
By using $window.localStorage.xxXX() the user has control over the localStorage value. The size of the data depends upon the browser. If you only use $localStorage then value remains as long as you use window.location.href to navigate to other page and if you use to navigate to other page then your $localStorage value is lost in the next page.
For local storage there is a module for that look at below url:
https://github.com/grevory/angular-local-storage
and other link for HTML5 local storage and angularJs
http://www.amitavroy.com/justread/content/articles/html5-local-storage-with-angular-js/
Use ngStorage For All Your AngularJS Local Storage Needs. Please note that this is NOT a native part of the Angular JS framework.
ngStorage contains two services, $localStorage and $sessionStorage
angular.module('app', [
'ngStorage'
]).controller('Ctrl', function(
$scope,
$localStorage,
$sessionStorage
){});
Check the Demo
There is one more alternative module which has more activity than ngStorage
angular-local-storage:
https://github.com/grevory/angular-local-storage
You can use localStorage for the purpose.
Steps:
add ngStorage.min.js in your file
add ngStorage dependency in your module
add $localStorage module in your controller
use $localStorage.key = value
I authored (yet another) angular html5 storage service. I wanted to keep the automatic updates made possible by ngStorage, but make digest cycles more predictable/intuitive (at least for me), add events to handle when state reloads are required, and also add sharing session storage between tabs. I modelled the API after $resource and called it angular-stored-object. It can be used as follows:
angular
.module('auth', ['yaacovCR.storedObject']);
angular
.module('auth')
.factory('session', session);
function session(ycr$StoredObject) {
return new ycr$StoredObject('session');
}
API is here.
Repo is here.
Hope it helps somebody!
Follow the steps to store data in Angular - local storage:
Add 'ngStorage.js' in your folder.
Inject 'ngStorage' in your angular.module
eg: angular.module("app", [ 'ngStorage']);
Add $localStorage in your app.controller function
4.You can use $localStorage inside your controller
Eg: $localstorage.login= true;
The above will store the localstorage in your browser application
Depending on your needs, like if you want to allow the data to eventually expire or set limitations on how many records to store, you could also look at https://github.com/jmdobry/angular-cache which allows you to define if the cache sits in memory, localStorage, or sessionStorage.
One should use a third party script for this called called ngStorage here is a example how to use.It updates localstorage with change in scope/view.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<!-- CDN Link -->
<!--https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js-->
<script src="angular.min.js"></script>
<script src="ngStorage.min.js"></script>
<script>
var app = angular.module('app', ['ngStorage']);
app.factory("myfactory", function() {
return {
data: ["ram", "shyam"]
};
})
app.controller('Ctrl', function($scope, $localStorage, $sessionStorage, myfactory) {
$scope.abcd = $localStorage; //Pass $localStorage (or $sessionStorage) by reference to a hook under $scope
// Delete from Local Storage
//delete $scope.abcd.counter;
// delete $localStorage.counter;
// $localStorage.$reset(); // clear the localstorage
/* $localStorage.$reset({
counter: 42 // reset with default value
});*/
// $scope.abcd.mydata=myfactory.data;
});
</script>
</head>
<body ng-app="app" ng-controller="Ctrl">
<button ng-click="abcd.counter = abcd.counter + 1">{{abcd.counter}}</button>
</body>
</html>
Related
My AngularJS app makes calls to an API which is currently hosted at one service, but was previously hosted at a different one, and in the near future is likely to be hosted yet somewhere else.
The URL is regularly changing. For example from
myfirst.heroku.com/app/user/mike/profile
to
mysecond.bluemix.com/app/user/mike/profile
etc.
Instead of changing the URL in every location everytime, I want to just have to change the part before the /app....
In an Angular App what is the best way to do this?
NOTE: Many of the URLs I use throughout the app, are in modules that are added as dependencies to my main app. So Module1 and Module2 both use the URL in their controllers and resources and are then included in MainApp. So a good solution for me needs to be accessible to all dependee apps. Is that possible.
I would like to suggest you that you must use angular constant, Its similar to a service but it creates a constant value which can be inject everywhere in our angular project.
This is how we can create constant
Constant service:
angular.module('AppName')
.constant('REST_END_POINT', 'https://rest.domain.com/');
Usages in controller:
angular.module('AppName')
.controller('CTRL_NAME', ['REST_END_POINT', '$scope', function(REST_END_POINT, $scope){
//your business logic.
]);
$location.host() is the client browser's 'prefix.domain.suffix'
You can inject $location into whatever scope or service.
angular.module('app',[]).run(function($rootScope, $location){
$rootScope.host = $location.host();
})
Plunk: http://plnkr.co/edit/gDgrlwZFyWNKUJgbHHKj?p=preview
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
</head>
<body>
<i>Host:</i>
<h1>{{host}}</h1>
<script>
angular.module('app',[]).run(function($rootScope, $location){
$rootScope.host = $location.host();
});
</script>
</body>
</html>
I do use request interceptor for this
csapp.factory('MyHttpInterceptor', [function () {
var requestInterceptor = function (config) {
var prefix = "http://api.example.com";
if (config.url.indexOf("/api/") !== -1) {
config.url = prefix + config.url;
}
}
}]);
configure this intercept in app.config like
csapp.config(["$httpProvider", function($httpProvider) {
$httpProvider.interceptors.push('MyHttpInterceptor');
});
now all your api requests would be prefixed with api.example.com.
i have some application settings that i want to retrieve from backend, so that they would be available to all of my application controllers via injection. What is the most angular-way to do that?
1) If i only needed settings for one or few controllers i could retrieve them via routing resolve method, but what about global application scope?
2) I could use the .run() method, but since call will be async i have no guaranties that my config will be loaded before i access controllers.
Currently my settings are returned as a json object, and my templates/html files are simply served by web server. So i cannot embed anything into script tags, parse html on the server side or any similar technique.
I would create a service for your settings. Then using the .run() method, called a service that returns your app settings data:
angular
.module('YourApp',[])
.service('Settings',function(){
this.data = {}
})
.run(function(Settings,$http){
$http
.get('/ajax/app/settings')
.success(function(data){
Settings.data = data
})
})
function Controller($scope,Settings){
// use your Settings.data
}
http://docs.angularjs.org/api/angular.Module#methods_run
There is a neat plugin to do the job. https://github.com/philippd/angular-deferred-bootstrap
You need to change bootstrap method
deferredBootstrapper.bootstrap({
element: document.body,
module: 'MyApp',
resolve: {
APP_CONFIG: function ($http) {
return $http.get('/api/demo-config');
}
}
});
angular.module('MyApp', [])
.config(function (APP_CONFIG) {
console.log(APP_CONFIG);
});
How can I start fetching data from the server as quickly as possible with Angular?
Currently, most of my page is populated asynchronously via a directive "fooload" placed at the root element:
<html lang="en" ng-app="myapp" fooload ng-controller="MyAppCtrl">
<head>
/* bunch of CSS, and other resources */
</head>
Which loads data into the scope via an http GET request:
angular.module('myapp.directives').
directive('fooload', function ($http) {
return {
link: function (scope, elm, attrs) {
$http.get('/foo').success(function (data) {
scope.foo = data;
});
}
};
});
Looking at the network panel, this call is being made in the browser AFTER the requests for the resources referenced in head. How can I make the call to load /foo data as quickly as possible on page load (if possible, even before loading angular itself)?
This is not really related to Angular, obviously Angular cannot start loading files before Angular has loaded itself. But if the resource (eg /foo) is cacheable by the browser you could add it to a manifest file: http://www.html5rocks.com/en/tutorials/appcache/beginner/
I solved this by:
a) fetching the data even before angular loads and storing it in a global variable (I hate using a global variable, but I couldn't think of another way.)
b) manually bootstrapping angular upon load of this data (my app doesn't work at all without the data)
var $data;
var ajax_transport = new XMLHttpRequest();
// Callback for AJAX call
function responseProcess() {
if (ajax_transport.readyState !== 4) {
return;
}
if (ajax_transport.responseText) {
$data = JSON.parse(ajax_transport.responseText);
angular.bootstrap(document, ['myApp']);
});
}
}
// Sending request
ajax_transport.open("GET", "/mydata", true);
ajax_transport.onreadystatechange = responseProcess;
ajax_transport.send();
Note: it's important to remove the tag ng-app="myapp" in your template to avoid automatic bootstrapping.
c) Using the data in my angular app:
scope.setupSomething($data);
d) Also, to ensure that this data call begins before any other resource load, I started using a resource loader. I liked HeadJs (http://headjs.com/) the most, but the angular folks seem to like script.js (https://github.com/angular/angular-phonecat/blob/master/app/index-async.html)
Criticism or improvements welcome.
Start by creating a new service that gets the resource and then bootstraps the document for angular upon success callback from the server.
angular.element(document).ready(function() {
calllService(function () {
angular.bootstrap(document);
});
});
https://stackoverflow.com/a/12657669/1885896
I'm new to AngularJS but I really like the way AngularJS works so I want to deployed it as client side for my Google cloud endpoint backend. Then I immediately get two problems:
1, Where to put the myCallback, so it's able to work into the ANgularJs controller?
<script src="https://apis.google.com/js/client.js?onload=myCallback"></script>
2, How I'm able to do the oauth2? and how the controller knows if the user authorized?
gapi.auth.authorize({client_id: myCLIENT_ID,
scope: mySCOPES,.....
Any help is appreciated.
For loading Google Javascript Library with AngularJs, the callback function passed to onLoad of Google Javascript Library is the function that bootstrap AngularJS, like this:
This goes to the final of html file:
<script src="https://apis.google.com/js/client.js?onload=startApp">
Then, in <head> section you bootstrap angular like this:
<script type='text/javascript'>
function startApp() {
var ROOT = 'http://<yourapi>.appspot.com/_ah/api';
gapi.client.load('myapifromgoogleendpoint', 'version1', function() {
angular.bootstrap(document, ["myModule"]);
}, ROOT);
}
</script>
As described by Kenji, you also need to remove ng-app directive from your html.
Regarding the callback - In order to access an Angular controller you need to use an injector (http://docs.angularjs.org/api/AUTO.$injector)
Simply create a global callback function, and then get reference to the controller from it like this:
window.callbackFunction() {
injector = angular.element(document.getElementById('YourController')).injector()
injector.invoke(function ($rootScope, $compile, $document) {
$rootScope.variable = "stuff you want to inject";
})
}
In this example I'm injecting the data to the rootScope, but this will also work for a specific controller scope (just inject $scope instead)
Can't help with the second question as I'm not familiar with gapi, though making auth2 calls from angularjs is quite straight forward.
Here you have details on how to use angularjs with google endpoints:
https://cloud.google.com/developers/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications?hl=es
What's the AngularJS way to access cookies? I've seen references to both a service and a module for cookies, but no examples.
Is there, or is there not an AngularJS canonical approach?
This answer has been updated to reflect latest stable angularjs version. One important note is that $cookieStore is a thin wrapper surrounding $cookies. They are pretty much the same in that they only work with session cookies. Although, this answers the original question, there are other solutions you may wish to consider such as using localstorage, or jquery.cookie plugin (which would give you more fine-grained control and do serverside cookies. Of course doing so in angularjs means you probably would want to wrap them in a service and use $scope.apply to notify angular of changes to models (in some cases).
One other note and that is that there is a slight difference between the two when pulling data out depending on if you used $cookie to store value or $cookieStore. Of course, you'd really want to use one or the other.
In addition to adding reference to the js file you need to inject ngCookies into your app definition such as:
angular.module('myApp', ['ngCookies']);
you should then be good to go.
Here is a functional minimal example, where I show that cookieStore is a thin wrapper around cookies:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="MyController">
<h3>Cookies</h3>
<pre>{{usingCookies|json}}</pre>
<h3>Cookie Store</h3>
<pre>{{usingCookieStore|json}}</pre>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
<script>
angular.module('myApp', ['ngCookies']);
app.controller('MyController',['$scope','$cookies','$cookieStore',
function($scope,$cookies,$cookieStore) {
var someSessionObj = { 'innerObj' : 'somesessioncookievalue'};
$cookies.dotobject = someSessionObj;
$scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };
$cookieStore.put('obj', someSessionObj);
$scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
}
</script>
</body>
</html>
The steps are:
include angular.js
include angular-cookies.js
inject ngCookies into your app module (and make sure you reference that module in the ng-app attribute)
add a $cookies or $cookieStore parameter to the controller
access the cookie as a member variable using the dot (.) operator
-- OR --
access cookieStore using put/get methods
This is how you can set and get cookie values. This is what I was originally looking for when I found this question.
Note we use $cookieStore instead of $cookies
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<script src="http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js"></script>
<script>
angular.module('myApp', ['ngCookies']);
function CookieCtrl($scope, $cookieStore) {
$scope.lastVal = $cookieStore.get('tab');
$scope.changeTab = function(tabName){
$scope.lastVal = tabName;
$cookieStore.put('tab', tabName);
};
}
</script>
</head>
<body ng-controller="CookieCtrl">
<!-- ... -->
</body>
</html>
Angular deprecated $cookieStore in version 1.4.x, so use $cookies instead if you are using latest version of angular. Syntax remain same for $cookieStore & $cookies:
$cookies.put("key", "value");
var value = $cookies.get("key");
See the Docs for an API overview. Mind also that the cookie service has been enhanced with some new important features like setting expiration (see this answer) and domain (see CookiesProvider Docs).
Note that, in version 1.3.x or below, $cookies has a different syntax than above:
$cookies.key = "value";
var value = $cookies.value;
Also if you are using bower, make sure to type your package name correctly:
bower install angular-cookies#X.Y.Z
where X.Y.Z is the AngularJS version you are running.
There's another package in bower "angular-cookie"(without the 's') which is not the official angular package.
FYI, I put together a JSFiddle of this using the $cookieStore, two controllers, a $rootScope, and AngularjS 1.0.6. It's on JSFifddle as http://jsfiddle.net/krimple/9dSb2/ as a base if you're messing around with this...
The gist of it is:
Javascript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('CookieCtrl', function ($scope, $rootScope, $cookieStore) {
$scope.bump = function () {
var lastVal = $cookieStore.get('lastValue');
if (!lastVal) {
$rootScope.lastVal = 1;
} else {
$rootScope.lastVal = lastVal + 1;
}
$cookieStore.put('lastValue', $rootScope.lastVal);
}
});
myApp.controller('ShowerCtrl', function () {
});
HTML
<div ng-app="myApp">
<div id="lastVal" ng-controller="ShowerCtrl">{{ lastVal }}</div>
<div id="button-holder" ng-controller="CookieCtrl">
<button ng-click="bump()">Bump!</button>
</div>
</div>
http://docs.angularjs.org/api/ngCookies.$cookieStore
Make sure you include http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js to use it.
Add angular cookie lib : angular-cookies.js
You can use $cookies or $cookieStore parameter to the respective controller
Main controller add this inject 'ngCookies':
angular.module("myApp", ['ngCookies']);
Use Cookies in your controller like this way:
app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) {
//store cookies
$cookies.putObject('final_total_price', $rootScope.fn_pro_per);
//Get cookies
$cookies.getObject('final_total_price'); }
AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.
We need to add angular-cookies.min.js file to use cookie feature.
Here is some method of AngularJS Cookie.
get(key); // This method returns the value of given cookie key.
getObject(key); //This method returns the deserialized value of given
cookie key.
getAll(); //This method returns a key value object with all the
cookies.
put(key, value, [options]); //This method sets a value for given
cookie key.
remove(key, [options]); //This method remove given cookie.
Example
Html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>
JavaScript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);
I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.
The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.
Now, if you want to integrate js-cookie with angular, it is as easy as something like:
module.factory( "cookies", function() {
return Cookies.noConflict();
});
And that's it. No jQuery. No ngCookies.
You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign + instead of also percent-encode it:
module.factory( "phpCookies", function() {
return Cookies
.noConflict()
.withConverter(function( value, name ) {
return value
// Decode all characters according to the "encodeURIComponent" spec
.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
// Decode the plus sign to spaces
.replace(/\+/g, ' ')
});
});
The usage for a custom Provider would be something like this:
module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
this.storeData = function( data ) {
phpCookies.set( "data", data );
};
this.containsStoredData = function() {
return phpCookies.get( "data" );
}
}]);
I hope this helps anyone.
See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103
For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md
Here's a simple example using $cookies. After clicking on button, the cookie is saved, and then restored after page is reloaded.
app.html:
<html ng-app="app">
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-cookies.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="appController as vm">
<input type="text" ng-model="vm.food" placeholder="Enter food" />
<p>My favorite food is {{vm.food}}.</p>
<p>Open new window, then press Back button.</p>
<button ng-click="vm.openUrl()">Open</button>
</body>
</html>
app.js:
(function () {
"use strict";
angular.module('app', ['ngCookies'])
.controller('appController', ['$cookies', '$window', function ($cookies, $window) {
var vm = this;
//get cookie
vm.food = $cookies.get('myFavorite');
vm.openUrl = function () {
//save cookie
$cookies.put('myFavorite', vm.food);
$window.open("http://www.google.com", "_self");
};
}]);
})();