Unable to send data from controller to component - angularjs

I have situation where I would like to configure component in html code. I have the following structure.
game.html which is served as in url like example.com/game/7999 which should show page for game 7999.
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>Providence</title>
<script src="/js/angular.js"></script>
<script src="/data-access/data-access.module.js"></script>
<script src="/data-access/data-access.service.js"></script>
<script src="/score-info/score-info.module.js"></script>
<script src="/score-info/score-info.component.js"></script>
<script src="/js/game.js"></script>
</head>
<body>
<div ng-controller="myController">
<p> {{ game_id }} </p>
<score-info game_id="{{ game_id }}"></score-info>
</div>
</body>
Corresponding game.js, which seem to work as game_id shows up correctly.
angular.module('myApp', [
'dataAccess',
'scoreInfo' ],
function($locationProvider){
$locationProvider.html5Mode(true);
});
angular.
module('myApp').
controller('myController', function($scope, $location) {
var split_res = $location.path().split('/');
var game_id = split_res[split_res.length-1];
$scope.game_id = game_id
});
My problem lies in component where I'm unable to inject the game_id. Here's score-info.component.js where the game_id does not become visible.
angular.
module('scoreInfo').
component('scoreInfo', {
templateUrl : '/score-info/score-info.template.html',
controller : function ScoreInfoController(dataAccess) {
self = this;
console.log(self.game_id) // self.game_id == undefined
dataAccess.game(self.game_id).then(function(game) {
self.game = game;
});
},
bindings : {
game_id : '<'
}
});
I noticed that some earlier answers recommended using a separate service of wiring up controller and component. That does not work for me as I need to be able to include varying number of scoreInfo -blocks in a single page.

I'm going to answer this myself. The answer was provided by JB Nizet in comments.
First problem was naming related. The code needs to stick with angular.js' naming convention and use gameId: '<' and use <score-info game-id="game_id">
Also < binding must have the reference in the element without curly braces: <score-info game-id="game_id">
Finally, the components controller needs to take in to the account breaking changes between angular 1.5 -branch and 1.6 -branch. See angular CHANGELOG. Specifically ScoreInfoController becomes
function ScoreInfoController(dataAccess) {
self = this;
self.$onInit = function() {
dataAccess.game(self.game_id).then(function(game) {
self.game = game;
})
}

Related

Finding a div in an AngualrJS ui-router view, using document.querySelector

Please see https://jsfiddle.net/mawg/fu9er5cy/3/
I modified an exciting Plunker (hence this is a little more complex than necessary to demonstrate my problem), and in <div ng-controller="myController">
I added <div id="myDiv">Can this be found?</div>
and in myController, I added:
if (document.querySelector('#myDiv') === null)
{
alert('Div not found !!');
}
else
{
alert('yay, Div found :-)');
}
The div can be seen by selecting "book info" and I naively thought that the controller's code, and, hence, document.querySelector() would be executed when I navigate to that state's view.
As you can see, it is evaluated immediately, and says that the div can not be found.
As you can also see, from my related question, I only want to find the div when I change state & navigate to the state which shows that view and, hence, its controller, so that I can document.querySelector the div and inject an ag-grid into it.
How can I do that?
1) Your <div id="myDiv">Can this be found?</div> exists in:
$stateProvider.state("details", {
url: "/details",
and this is not your default route: $urlRouterProvider.otherwise("/")
so let's change it to $urlRouterProvider.otherwise("/details")
2) I don't know the golal of:
getID: function($timeout) {
return $timeout(function() {
console.log("value resolved")
//$scope.Company="Cognizant";
}, 1000)
}
but it stucks your route for 1 sec. You start to render the view only after 1 sec.
so I removed this code snippet.
3) You try to check the id in the same digest cycle with view rendering, so you get a failure. to trigger the digest cycle or enter to the end of queue you can add some zero timeout:
$timeout(function(){
if (document.querySelector('#myDiv') === null)
{
alert('Div not found !!');
}
else
{
alert('yaya, Div found :-)');
}
},0)
fixed example Fiddle
Hope it will give you some input to figure out :)
You can run a check whenever something in the DOM changes, and then remove the listener, once the div is found
function func() {
if (document.querySelector('#myDiv') !== null) {
document.documentElement.removeEventListener('DOMSubtreeModified', func);
alert('yaya, Div found :-)');
}
}
document.documentElement.addEventListener('DOMSubtreeModified', func);
func();
in trying to reply to #Maxim, I coded a Plunker from scratch.
It does exactly what I want it to.
It seems that every time a router state is entered, its controller is initialized, and in the initialization code I can find the div.
There is something wrong with my much larger app, which does not find the div. So, I will start with the Plunker and drop my app into it, piece by piece, until I get it to work.
I post this answer in the hope that it will help someone in future. Here's the code:
alpha.html
<div>
<h1>Alpha</h1>
</div>
<a ui-sref="beta" ui-sref-active="beta">Beta</a>
beta.html
<div id="beta_div">
<h1>Beta</h1>
</div>
<a ui-sref="alpha" ui-sref-active="alpha">Alpha</a>
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link type="text/css" rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="application/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="application/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="application/javascript"
src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script type="application/javascript"
src="//rawgit.com/angular-ui/ui-router/0.2.13/release/angular-ui-router.js"></script>
<script type="application/javascript" src="app.js"></script>
<script type="application/javascript" src="controllers.js"></script>
</head>
<body ui-view></body>
</html>
app.js
angular.module('app', [
'ui.router'
]);
angular.module('app').config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/alpha');
$stateProvider.state('alpha', {
url: '/alpha',
templateUrl: './alpha.html',
controller: 'alphaController'
});
$stateProvider.state('beta', {
url: '/beta',
templateUrl: './beta.html',
controller: 'betaController'
});
}
]);
controllers.js
angular.module('app').controller('alphaController', ['$state',
function ($state) {
}
]);
angular.module('app').controller('betaController', ['$state',
function ($state) {
if (document.querySelector('#beta_div') === null) {
alert('Div not found !!');
}
else {
alert('Yay, Div found :-)');
}
}
]);

Can I create global function with $window and call it in controllers in angularJS? [duplicate]

If I have a utility function foo that I want to be able to call from anywhere inside of my ng-app declaration. Is there someway I can make it globally accessible in my module setup or do I need to add it to the scope in every controller?
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
If that's not an option for you, you can add it to the root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
That way, all of your templates can call globalFoo() without having to pass it to the template from the controller.
You can also combine them I guess:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
</body>
</html>
Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.
Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.
Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.
AngularJs has "Services" and "Factories" just for problems like yours.These are used to have something global between Controllers, Directives, Other Services or any other angularjs components..You can defined functions, store data, make calculate functions or whatever you want inside Services and use them in AngularJs Components as Global.like
angular.module('MyModule', [...])
.service('MyService', ['$http', function($http){
return {
users: [...],
getUserFriends: function(userId){
return $http({
method: 'GET',
url: '/api/user/friends/' + userId
});
}
....
}
}])
if you need more
Find More About Why We Need AngularJs Services and Factories
I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. globalFunctions.foo = myFunc();. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions; and I instantly have access to any function I added to the globalFunctions object in the global script.
This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.

Make a default function for all controllers Angular JS [duplicate]

If I have a utility function foo that I want to be able to call from anywhere inside of my ng-app declaration. Is there someway I can make it globally accessible in my module setup or do I need to add it to the scope in every controller?
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
If that's not an option for you, you can add it to the root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
That way, all of your templates can call globalFoo() without having to pass it to the template from the controller.
You can also combine them I guess:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
</body>
</html>
Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.
Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.
Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.
AngularJs has "Services" and "Factories" just for problems like yours.These are used to have something global between Controllers, Directives, Other Services or any other angularjs components..You can defined functions, store data, make calculate functions or whatever you want inside Services and use them in AngularJs Components as Global.like
angular.module('MyModule', [...])
.service('MyService', ['$http', function($http){
return {
users: [...],
getUserFriends: function(userId){
return $http({
method: 'GET',
url: '/api/user/friends/' + userId
});
}
....
}
}])
if you need more
Find More About Why We Need AngularJs Services and Factories
I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. globalFunctions.foo = myFunc();. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions; and I instantly have access to any function I added to the globalFunctions object in the global script.
This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.

Can I make a function available in every controller in angular?

If I have a utility function foo that I want to be able to call from anywhere inside of my ng-app declaration. Is there someway I can make it globally accessible in my module setup or do I need to add it to the scope in every controller?
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
If that's not an option for you, you can add it to the root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
That way, all of your templates can call globalFoo() without having to pass it to the template from the controller.
You can also combine them I guess:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
</body>
</html>
Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.
Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.
Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.
AngularJs has "Services" and "Factories" just for problems like yours.These are used to have something global between Controllers, Directives, Other Services or any other angularjs components..You can defined functions, store data, make calculate functions or whatever you want inside Services and use them in AngularJs Components as Global.like
angular.module('MyModule', [...])
.service('MyService', ['$http', function($http){
return {
users: [...],
getUserFriends: function(userId){
return $http({
method: 'GET',
url: '/api/user/friends/' + userId
});
}
....
}
}])
if you need more
Find More About Why We Need AngularJs Services and Factories
I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. globalFunctions.foo = myFunc();. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions; and I instantly have access to any function I added to the globalFunctions object in the global script.
This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.

How to access cookies in AngularJS?

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

Resources