How can I load dynamically my AngularJS application dependencies - angularjs

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

Related

First Angular app not outputting from controller

I'm still very new at this and this is my first attempt to making an app without following any guide. For some reason my output in the webpage is {{$scope.products}} instead of the actual values. Can anyone tell my why it won't load the angular code from the controller?
index.html
<<!doctype html ng-app="MyFirstApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainController as ctrl">
{{ctrl.name}}
{{"Hello World"}}
</body>
</html>
app.js
var app = angular.module('MyFirstApp', [])
.controller('MainController', function(){
this.name = "Joe";
});
Your snippet contains some errors:
<!doctype html ng-app="MyFirstApp"> : ngApp directive is too high. Please put it in the <body> tag at least.
ng-controller="MainController as ctrl": if it is your very first AJS example, be aware that controllerAs is a best practice, but a bit advanced. This choice will condition slightly the controller code.
{{products.title}}: products is an array!
... .controller('MainController',[$scope function($scope){: the second argument of controller method is an array, so between $scope and function a comma is needed. In your case the array must be: ['$scope',function($scope){...}]. For more info pls see https://docs.angularjs.org/guide/di
$scope.products = [...]; : in order to avoid controllerAs antipattern you must use this.products.
Please update your code.
you need to put the dependancy to your controller between '' and
you are missing some thing after $scope
.controller('MainController',['$scope',function($scope){
}]);
and there are no iterate for the array in your controller to be bind in html
var app = angular.module('MyFirstApp', [])
.controller('MainController', function(){
this.name = "Joe"
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyFirstApp" ng-controller="MainController as ctrl">
{{ctrl.name}}
</div>
AngularJS documentation can be quite confusing.
Assigning values to the $scope is considered a bad practice. This is one of the things that the controllerAs syntax solves. So instead of adding the products to $scope.products -- add them to this.name.
Then in your view you will access them with {{ctrl.name}}
I hope this helps.

Directive not working in angularjs

I am newbie to Angularjs. I am trying to create simple directive with the following code:
View:
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<user-info></user-info>
</div>
</body>
</html>
Controller:
myapp = angular.module("myapp", []);
myapp.directive('userInfo', function() {
var directive = {};
directive.restrict = 'E'; /* restrict this directive to elements */
directive.template = "My first directive: ";
return directive;
});
I am following this Tutorial to learn directive
http://tutorials.jenkov.com/angularjs/custom-directives.html
I am getting error:
http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.3.14%2F%24injector%2Fnomod%3Fp0%3DmyApp%0A%20%20%20%20at%20Error%20(native)%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A6%3A417%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A412%0A%20%20%20%20at%20a%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A53)%0A%20%20%20%20at%20w.bootstrap%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A296)%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A35%3A46%0A%20%20%20%20at%20s%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A7%3A302)%0A%20%20%20%20at%20g%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A34%3A399)%0A%20%20%20%20at%20ab%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A38%3A135)%0A%20%20%20%20at%20d%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A17%3A381
Here is my codepen link
http://codepen.io/anon/pen/NGNKxz
You have error in the name of your app :
myapp = angular.module("myApp", []); // not 'myapp'
Add Your Directive
You need to add the directive to your html like so
<script src="path/to/your/directive.js"></script>
or if your working from one module you will link to the main module. But please restructure your app like this it will keep code up to standard and clean.
I have a git hub repo where I am building an app in this structure here. Best of luck.
Note
You are using angular min. Min is great for production because its small and faster to load but your in development at the moment so use the full version so you can capture errors better with the browser console.
Looks like you did not declare the controller myCtrl. Your directive looks fine.
myapp.controller('myCtrl', function() {
});
Is it the current version of your html file ?
Because you might need to link your controller, between head tags, insert :
<script src="the js file which contains your controller"></script>
or
<script>Your controller</script>

Angular controller not being instantiated

In the following piece of code, I create a simple controller that does not get instantiated.
var app = angular.module('newstalk',[]);
app.controller('articlectrl',[function(){
console.log("hi");
}]);
The corresponding HTML for it is this:
<html ng-app='newstalk'>
<!-- I have also included both angular js file and my js file in html-->
<body ng-controller='articlectrl'></body>
</html>
The string hi is not getting logged.

Error injecting custom service into another custom service

Now that I have my script files referenced in my view template, I am having trouble injecting the first one into the second one.
If I unplumb the dependency that LearnerService has on SCORMService, everything displays according to plan, but is of course nonfunctional because LearnerService relies on SCORMService to accomplish its purpose. When I try to actually use my SCORMService within my LearnerService, I get Michael Bay explosions and sad trombones.
So, I'm using ngRoute. That might be important; maybe not.
I'll list my app.js, my script ordering in index.html, learnerServices.js, SCORMServices.js, and controllers.js
app.js
'use strict';
var app = angular.module('client', [
'ngRoute'
,'controllers'
,'services.proxy.scorm'
,'services.proxy.lms'
]);
index.html
...
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/SCORMService.js"></script>
<script src="js/LearnerServices.js"></script>
</head>
<body>
<div class="view-container">
<div ng-view class="view-frame"></div>
</div>
</body>
</html>
LearnerServices.js
'use strict';
var learnerServices = angular.module('services.proxy.lms',['scorm-service']);
learnerServices.factory('LearnerService', [ 'scorm-service', function(){
return true;
}]);
SCORMService.js
'use strict';
var services = angular.module('services.proxy.scorm', []);
services.factory('scorm-service',function(){
var foo = {};
foo.bar = "snazzy jazzy";
return foo;
});
I seem to be attempting to corner the market on stupid mistakes today. Can anyone see what stupid mistake I did this time?
This line should be:
var learnerServices = angular.module('services.proxy.lms',['services.proxy.scorm']);
Notice in your code you are saying the module has a dependency on scorm-service however the dependency for the module is on services.proxy.scorm
Load your dependencies first in your html. That'll help.

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