I have two files
test1.js
angular.module("test1",[]).controller("test1Ctrl",function(){
// some code
})
and
test2.js
angular.module("test2",[]).controller("test2Ctrl",function(){
//some code
})
app.js
var app = angular.module("testApp",['test1','test2']);
My question is how I can inject my both controller in app.js from test1.js and test2.js using same module and not using module test1 and test2?
If you want to keep controllers in separate file then,
app.js
var app = angular.module("testApp",[]);
test1.js
app.controller("test1Ctrl",function(){
// some code
})
test2.js
app.controller("test2Ctrl",function(){
// some code
})
Finally include js files in html,
<script src="app.js"></script>
<script src="test1.js"></script>
<script src="test2.js"></script>
I'm having an issue using the Google Api in my angularjs 1.3 (SPA using ui.router). Per the google api instructions, I added a reference to the client.js file with a call back in my index.html head,
<html ng-app="myApp">
<head>
<script src="Scripts/jquery-2.1.3.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-ui-router.min.js"></script>
<script>
function LoadGAPI() {
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=LoadGAPI"></script>
As I understand, client.js will asynchronously load the full client api, and when complete call the defined function LoadGAPI.
Sometimes LoadGAPI is called before my angular app .run is called, and sometimes it is not. I don't mind that it loads asynchonously.. but how can I alert my angular app that it is indeed ready for use?
I faced something similar before and there are two ways of solving it, one is delaying the whole angular's bootstrapping till the other library gets loaded by triggering it manually after LoadGAPI and dom ready, something like:
var n = 0;
function LoadGAPI () {
// Only pass after the first call
if (n++) {
angular.bootstrap(angular.element(document).find('html'), ['app']);
}
};
angular.element(document).ready(LoadGAPI);
and the other one is ensuring the library's presence only for the ui-router states needing it using resolve:
State
$stateProvider
...
.state('some.state', {
url : '/some',
templateUrl: 'view/some.state.html',
controller : 'some.state',
resolve : GAPI.resolver
})
...
Resolver
var GAPI = {
ready : false,
resolver: {
api: ['$q', function($q) {
if (!GAPI.deferred) {
GAPI.deferred = $q.defer();
}
if (GAPI.ready) {
GAPI.deferred.resolve();
}
return GAPI.deferred.promise;
}]
}
};
window.LoadGAPI = function () {
GAPI.ready = true;
if (GAPI.deferred) {
GAPI.deferred.resolve();
}
};
The second one can be simplified, but I hope you get the idea.
my $http post body is too large and i need to make six different $http calls with different post content. i can't keep the body of the post messages (which is nothing but a valid json string) in my controller.js as it bloats it and becomes ugly. is there anything like require in javascript (or) import statements in python that i can use to put all constants in one module and import it into my app.js?
lib.js contents::::::::
var a = 'hello~'
module.exports = a
app.js::::::
a = require('lib')
app.controller('aController', function($scope){
console.log(a) //this must print hello~
}
I don't know if I understood well, but the solutions it's to add the 'lib.js' to the HTML before you add the app.js. Like this:
<script src="js/lib.js"></script>
<script src="js/app.js"></script>
And it's not necessary to make the export, you 'lib.js' may look like that:
var a="hello";
And in your app.js put console.log(a)
You can create a module that holds constants and is included in your js build process and use $provide.constant('constantName', constantObj); to provide the value. then you can just import the module and then the provider in your controller by doing:
app.module('this.aController', ['constantsModule']);
app.controller('aController', [
'constantName',
'$scope',
function ($scope) {
console.log(a);
}
]);
Let's say, I have HTML like this
<html ng-app='CoreAngular_App'>
<script>
var CoreAngular_AppObj = angular.module('CoreAngular_App', ['importantModule1', 'importantModule2', 'customModule1', 'customModule2', 'customModule3']);
</script>
<!-- here goes html structure with lot of ng-controller -->
<script>
//controller example
CoreAngular_AppObj.controller('MyControllerX', function($scope, myCustomModule2) {
}
</script>
</html>
It works, but as I have a lot of controllers and I don't know which of them will used, I want to load this list ['customModule1', 'customModule2', 'customModule3'] dynamically
I will glad to get something like this.
<html ng-app='CoreAngular_App'>
<script>
var CoreAngular_AppObj = angular.module('CoreAngular_App', ['importantModule1', 'importantModule2']);
</script>
<!-- here goes html structure with lot of ng-controller -->
<script>
// ADD myCustomModule2 TO CoreAngular_AppObj HERE
//controller example
CoreAngular_AppObj.controller('MyControllerX', function($scope, myCustomModule2) {
}
</script>
</html>
Is it possible? And how?
Thanks
I'll try to make an example of what either may look like.
Inline - from backend logic -
// Create list from rendered array.
var modules = ['customModule1', 'customModule3']; // ex: print json_encode($arrayStr);
// Add a custom module
angular.module('myCustom', modules);
//Inject the custom module
angular.module('CoreApp', ['importantModule1', 'importantModule2', 'myCustom']);
angular.bootstrap docs
Remember to remove ng-app
var app = angular.module('CoreApp', []);
someReadyFunction(){
// figure out which moules here
angular.bootstrap(document, ['CoreApp', 'customModule1', 'customModule3']);
}
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");
};
}]);
})();