AngularJS - Injecting a Provider - javascript

EDIT: using YEOMAN to scaffold my app,
I have the following YEOMAN generated provider
'use strict';
angular.module('myApp')
.provider('myProvider', function () {
// Private variables
var salutation = 'Hello';
// Private constructor
function Greeter() {
this.greet = function () {
return salutation;
};
}
// Public API for configuration
this.setSalutation = function (s) {
salutation = s;
};
// Method for instantiating
this.$get = function () {
return new Greeter();
};
});
and I'm trying inject it in my app config like so:
'use strict';
angular.module('myApp', [
'ngRoute',
'myProvider'
])
.config(function ($routeProvider, myProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
And I get the following error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module lpSocialApp due to:
Error: [$injector:modulerr] Failed to instantiate module myProvider due to:
Error: [$injector:nomod] Module 'myProvider' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
What am I missing?

I can see two mistakes in your code:
1) You cannot inject 'myProvider' in your application module since 'myProvider' is defined in your application module.
2) The name of 'myProvider' is wrong, Angular automatically append 'Provider' to your provider.
Here is the fix:
1) Define your provider in a dedicated module and add this new module in your application module dependencies.
2) Rename your provider to 'my' (or inject 'myProviderProvider' in your config function) :
angular.module('myProviderModule', [])
.provider('my', function () { // or 'myProvider'
// Private variables
var salutation = 'Hello';
// Private constructor
function Greeter() {
this.greet = function () {
return salutation;
};
}
// Public API for configuration
this.setSalutation = function (s) {
salutation = s;
};
// Method for instantiating
this.$get = function () {
return new Greeter();
};
});
angular.module('myApp', [
'ngRoute',
'myProviderModule'
])
.config(function ($routeProvider, myProvider) { // or 'myProviderProvider'
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
See this fiddle: http://jsfiddle.net/Z3k2s

You are confusing provider with modules. Modules include set of providers, services and factories.
You also should NOT add provider suffix when defining a provider, or else you have to inject it like myProviderProvider.
Also you look like you are confusing the syntax on angular.module:
// create a new module foo.bar with dependency to ngRoute
angular.module('foo.bar', ['ngRoute']);
// create a new module woo.hoo with NO dependency
angular.module('woo.hoo', []);
// get already created module foo.bar
angular.module('foo.bar')
Your code fixed:
'use strict';
angular.module('someModule', [])
.provider('my', function () {
// Method for instantiating
this.$get = function () {
return {}// return something
};
});
'use strict';
angular.module('myApp', [
'ngRoute',
'someModule'
])
.config(function ($routeProvider, myProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});

You are attempting to load a dependent module named myProvider:
angular.module('myApp', [
'ngRoute',
'myProvider'
])
myProvider is already in the myApp module, so you can do this:
angular.module('myApp', [
'ngRoute'
])
.config(function ($routeProvider, myProvider) {

Related

angular injection when minified

This code works but not when minified... What should I do?
I get this error Error:
$injector:strictdi
Explicit annotation required
// app.js
angular
.module('app', [route, 'templates']);
angular
.module('app')
.config(config);
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController',
controllerAs: 'vm'
});
$locationProvider.html5Mode(true);
}
angular
.module('app')
.controller('HomeController', HomeController);
function HomeController() {
var vm = this;
vm.header = 'Home';
}
// home.html
{{ vm.header }}
Angular tries to implicit loads dependencies by the arguments name and it works fine as long as the argument name is the same as the dependency you want to load.
For example,
function config($routeProvider, $locationProvider) {
...
}
This will trigger angular to inject the function with the $routeProvider and the $locationProvider but what happens if you minify the code to this:
function config(a, b) {
...
}
Angular will now try to inject the function with a and b (which does not exist). Therefore, you need to explicitly tell angular what dependencies you want to inject. You can either do it with inline bracket notation:
// bracket notation
angular
.module('app')
.config(['$routeProvider', '$locationProvider', config]);
function config($routeProvider, $locationProvider) {
...
}
... or alternatively with the $inject property:
// $inject property
angular
.module('app')
.config(config);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
...
}
Since you're using strict mode (most probably 'use strict' somewhere in code), you must explicitly inject the dependencies.
You can do like this
config.$inject = [$routeProvider, $locationProvider];
You can try this
angular
.module('app')
.config(config);
config.$inject = ['$routeProvider','$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController',
controllerAs: 'vm'
});
$locationProvider.html5Mode(true);
}
})();
(function () {
'use strict';
angular
.module('plunker')
.controller('HomeController',HomeController);
HomeController.$inject = [];
function HomeController() {
var vm = this;
}
})();

Loading external modules while lazy loading in angular

I am able to lazy load angularjs with the help of requirejs. But, how can I load modules that needs to be associated to the controller?
My example configuration in app.js looks like the following, loading all the providers and keeping a reference.
var app = angular.module('myApp', ['ui.router'])
var cacheProviders = {};
app.getProvider = function () {
return cacheProviders.$provide;
}
app.getCompileProvider = function () {
return cacheProviders.$compileProvider;
}
app.getControllerProvider = function () {
return cacheProviders.$controllerProvider;
}
app.getFilterProvider = function () {
return cacheProviders.$filterProvider;
}
app.config(['$stateProvider', '$urlRouterProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
function ($stateProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
(function () {
cacheProviders.$controllerProvider = $controllerProvider;
cacheProviders.$compileProvider = $compileProvider;
cacheProviders.$filterProvider = $filterProvider;
cacheProviders.$provide = $provide;
})();
var lazyCtrlLoad = function (controllerName) {
return ["$q", function ($q) {
var deferred = $q.defer();
require([controllerName], function () {
deferred.resolve();
});
return deferred.promise;
}];
}
$stateProvider.state('main.view2b', {
url: '/view2b',
templateUrl: 'forms/empl/searchEmplForm.html',
controllerAs: 'srchC',
controller: 'searchEmplCtrl',
resolve: {
loadOtherCtrl: lazyCtrlLoad('searchEmplCtrl')
}
})
In my other module, I am trying to register controllers, load services..
define([
'angular', 'angularResource'
], function (angular) {
angular.module('myApp')
.getControllerProvider()
.register(ctrl, ...)
But, while loading service below, I need access to $resource which is part of ngResource module in angularResource.
angular.module('myApp')
.getProvider().service('deptService', ['$resource', function ($resource) {
return $resource('/dept/:dept', {dept: '#_dept'});
}])
How can I load ngResource while initalizing the javascript controllers/services lazily?
Take a look to AngularAMD here. It allows you to load controllers in the ui-router without using lazyload. This AngularAMD is used to integrate requireJs and Angular.
$stateProvider
.state('home', {
url: '',
views: {
'#': angularAmd.route({
templateUrl: 'ngApplication/application/shared/layouts/basic/basicTplView.html',
controllerUrl: 'ngApplication/application/shared/layouts/basic/basicTplCtrl.js',
controller: 'basicTplCtrl'
}),
'header#home': angularAmd.route({
templateUrl: 'ngApplication/application/shared/layouts/header/headerView.html',
controllerUrl: 'ngApplication/application/shared/layouts/header/headerCtrl.js',
controller: 'headerCtrl'
})
},
});
Also, you are using requirejs, you can load all the dependencies for an specific controller using the define syntax of requireJs. Let's say you want to create a loginCtroller in a separately file, and this controller depends on another angular service:
define(['app', 'transformRequestAsFormPostService'], function (app) {
app.controller('loginCtrl', ['$scope', '$rootScope', '$sce', '$http', '$state', 'transformRequestAsFormPostService', function ($scope, $rootScope, $sce, $http, $state, transformRequestAsFormPost) {
$scope.login = function () {
/*do something here using the service*/
};
}]);
});
Here, the dependency called transformRequestAsFormPostService is another file, I defined it in the main.js (requireJs confifguration file) and it's defined using the same approach than the loginCtrol. Now I am using it in my project and its working so far so good.
Regards,
Ernesto

ngRoute dependency injection error but angular-route.js.min is loaded

I can't figure out why the module is failing to load on ngRoute. I have angular and angular-route scripts loading from cdn but I'm still getting the error Error: $injector:modulerr
Module Error
<!--Angular-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-route.min.js"></script>
<script src="app/index.js"></script>
<script src="app/components/blog/blogControllers.js"></script>
// index.js
'use strict';
var pdizzApp = angular.module('pdizzApp', [
'ngRoute',
'blogControllers'
]);
pdizzApp.config(['$routeProvider'], function ($routeProvider) {
$routeProvider
.when('/blog', {
templateUrl: 'blog/view/blog-list.html',
controller: 'BlogListController'
})
.otherwise({
redirectTo: '/blog'
})
});
//blogControllers.js
'use strict';
var blogControllers = angular.module('blogControllers', []);
blogControllers.controller('BlogListController', ['$scope', '$http',
function ($scope, $http) {
$http.get('/api/blog/post').success(function (data) {
$scope.posts = data._embedded.post;
});
$scope.toDate = function(date) {
return new Date(Date.parse(date));
}
}]);
Your config block should look as follows, i.e. the method needs to be declared inside the array that you pass to the config method:
pdizzApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/blog', {
templateUrl: 'blog/view/blog-list.html',
controller: 'BlogListController'
})
.otherwise({
redirectTo: '/blog'
});
}]);

All AngularJS Controllers Not Loading with LazyLoad

I am trying to lazy load my controllers for my AngularJS app I built along side with requireJS. I have created a custom "lazyLoad" library that creates a resolve object in app.config() routes (also I am using ui-router). If I code the state (without my library) to look like so it works
define(['angular', 'lazyLoader', 'uiRouter'], function(angular, lazyLoader, uiRouter){
var app = angular.module('myApp', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) {
window.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
$urlRouterProvider.otherwise('/');
$stateProvider
.state('campaigns', {
url:'/campaigns',
views: {
"top-nav" : {
templateUrl: 'views/home/top-nav.html',
resolve : {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require(['../app/controllers/header-controller'], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
}
},
"fullpage": {
templateUrl: 'views/home/index.html',
resolve : {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require(['../app/controllers/home-controller'], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
}
//controller: 'home-controller'
}
}
});
});
return app;
});
If I attempt to replace the resolve object with my library function it looks would look like this:
define(['angular', 'lazyLoader', 'uiRouter'], function(angular, lazyLoader, uiRouter){
and
.state('home', lazyLoader.route({
url:'/',
views: {
"top-nav" : {
templateUrl: 'views/home/top-nav.html',
controllerUrl: '../app/controllers/header-controller'
},
"fullpage": {
templateUrl: 'views/home/index.html',
controllerUrl: '../app/controllers/home-controller'
}
}
}));
lazyLoader.js
define(function () {
'use strict';
function LazyLoader() {}
LazyLoader.prototype.route = function(config){
var controllerPath;
if(config && config.views){
var singleView = Object.keys(config.views);
for(var i in singleView){
var viewName = singleView[i];
controllerPath = config.views[viewName].controllerUrl;
delete config.views.controllerUrl;
config.views[viewName].resolve = {
load : ['$q', '$rootScope', function($q, $rootScope){
var d = $q.defer();
require([controllerPath], function() {
$rootScope.$apply(function(){
d.resolve();
});
});
return d.promise;
}]
};
}
}
return config;
}
return new LazyLoader();
});
Example Controller
define(['app/module'], function (module) {
lazy.controller('header-controller', ['$scope', function ($scope) {
// stuff here
}]);
});
On a side note I plan on implementing something better than attaching lazy variable to window.
When I code the router like the first example it works. When I use my lazyLoader the one of the two views loads it's controller, the second view's controller's file is started to load (console.logs at the beginning show this) but it cannot resolve "module" in the example above.
link to error: AngularJS Error
Again this issue only happens when using my lazyloader which is producing the same resolve object that I have hard coded in for the version that works.
I have searched high and low and there are a lot of resources out there but I could not find anything that addressed this issue.
Any advice is appreciated!
You are taking too much pain to do lazy loading of controllers & services. There is simple approach to lazy load files with ocLazyLoad. This article might help you resolve the same issue.
https://routerabbit.com/blog/convert-angularjs-yeoman-spa-lazyload/
What you should do is
Add a reference of ocLayzLoad & updated JS files’ reference to load on demand from app.js or .html file of their views.
`bower install oclazyload --save-dev`
Now load the module ‘oc.lazyLoad’ in application. Update app.js file
angular
.module('helloWorldApp', [
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'oc.lazyLoad',
])
Load JS file by adding reference of JS in .html file
<div oc-lazy-load="['scripts/controllers/about.js', 'scripts/services/helloservice.js']">
<div ng-controller="AboutCtrl as about">
Your html goes here
</div>
</div>
If you using Grunt, update Gruntfile to uglyfy, renamed file name & update references in the final .html or .js file.
On the 'myApp' module definition, shouldn't you be returning app variable instead of myApp?
And to avoid exposing lazy to window, you could define it as a property of app variable, this way when you define new functions, you require app first and you can use it:
app.js:
app.lazy = {
controller: $controllerProvider.register,
directive: $compileProvider.register,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
...
return app;
controller.js:
define(['app'], function (app) {
app.lazy.controller('header-controller', ['$scope', function ($scope) {
// stuff here
}]);
});

Injecting angular controller in jasmine

I have read through many examples in regards to injecting controllers into a jasmine unit test, however I keep getting "Error: [ng:areq] http://errors.angularjs.org/undefined/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined".
Here is my code:
main.spec.js:
'use strict'
describe("Testing Main Controller", function(){
var scope, controller;
var dummyFunction = function(){};
var defaultDocument = {
_id: "123456"
};
beforeEach(module('app.controllers'));
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('MainCtrl', {
$scope: scope,
SearchService: dummyFunction,
ResultsService: dummyFunction,
FacetService: dummyFunction,
EsDateService: dummyFunction,
Likes: dummyFunction,
Bookmarks: dummyFunction
});
}));
describe("Likes", function(){
it('shall give the user the ability to like a document that is currently being displayed.', function(){
scope.updateLike([defaultDocument]);
expect(defaultDocument.isLiked).toBe(true);
});
it('shall give the user the ability to remove a like from a document that is currently being displayed.', function(){
defaultDocument.isLiked = true;
scope.updateLike([defaultDocument]);
expect(defaultDocument.isLiked).toBe(true);
});
});
});
main_controller.js:
'use strict';
angular.module('app.controllers')
.controller('MainCtrl', function($scope, SearchService, ResultsService, FacetService, EsDateService, Likes, Bookmarks) {
});
app.js:
angular.module('app.services', ['ngResource', 'elasticjs.service']);
angular.module('app.controllers', [ 'app.services']);
var app = angular.module('app', [
'ui.bootstrap',
'elasticjs.service',
'app.services',
'app.controllers',
'app.config',
'facet.directives',
'ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
controller: 'SearchCtrl',
templateUrl: 'views/search/search.html'
})
.when('/journal', {
controller: 'JournalCtrl',
templateUrl: 'views/journal/journal.html'
})
.otherwise({
redirectTo: '/'
});
}
]);
app.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix("!");
}
]);
When I attach MainCtrl to app rather than app.controllers it seems to find MainCtrl. What am I doing wrong?
You don't need to re-declare dependencies for app module, as app module injects app.controllers
beforeEach(module('app'));
Quick example how it can be solved - http://jsfiddle.net/PtXFb/

Categories

Resources