angular injection when minified - javascript

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

Related

Angularjs: Inject Service in app.config such that to safeguard against minification

I am trying to inject a service in app.config as illustrated in Inject service in app.config. However, minification breaks the app. How to overcome this?
This doesn't work with minification:
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
//Following method doesn't work with minification
data: getData
}
})
function getData (dbService) {
return dbService.getData();
}
}]);
Please note the following code doesn't work: (Typescript does not allow compilation)
['dbService',function getData(dbService){
return dbService.getData();
}]
In order to safeguard against minification, you need to annotate (see Dependency Annotation here) the data function like you did with the config function.
There are two ways to do this.
1.
Instead of passing a function, pass an array with the names of the dependencies and the function
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
//annotate this to prevent against minification
data: ['dbService', getData]
}
})
function getData (dbService) {
return dbService.getData();
}
}]);
2.
Add your dependencies to a $inject property on your function
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
//function annotated below
data: getData
}
})
//annotate this function with $inject so proper dependencies injected after minification
getData.$inject = ['dbService'];
function getData (dbService) {
return dbService.getData();
}
}]);

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

Angularjs Restful using ngResource not working

I am trying to expose restful web service using angularjs ngResource using java as my backend everything seems to be correct but don't know What is wrong with my code
nothing gets displayed in browser help me with this
service.js
'use strict';
var employeeServices = angular.module('myApp.services',['ngResource']);
employeeServices.factory('Employees',['$resource',function ($resource){
return $resource('my service link', {},{
query:{method:'GET',isArray:true}
});
}]);
Controller.js
'use strict';
angular.module('myApp.controllers',[]).
controller('Myctrl1',['$scope','Employees',function ($scope ,Employees){
$scope.allemployees = Employees.query();
}]).
controller('Myctrl2',[function (){
}]);
app.js
'use strict';
angular.module("myApp", [
'ngRoute',
'myApp.controllers',
'myApp.services'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1',{templateUrl:'partials/partials.html',controller:'Myctrl1'});
$routeProvider.when('/view2',{templateUrl:'partials/partials1.html',controller:'Myctrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
If you want to use service of one module in another module you have to inject it.
service.js
'use strict';
var employeeServices = angular.module('myApp.services', ['ngResource']);
employeeServices.factory('Employees', ['$resource', function ($resource) {
return $resource('my service link', {}, {
query: { method: 'GET', isArray: true }
});
}]);
Controller.js
'use strict';
angular.module('myApp.controllers', ['myApp.services']).
controller('Myctrl1', ['$scope', 'Employees', function ($scope, Employees) {
$scope.allemployees = Employees.query();
}]).
controller('Myctrl2', [function () {
}]);
app.js
'use strict';`enter code here`
angular.module("myApp", [
'ngRoute',
'myApp.controllers',
'myApp.services'
]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view1', { templateUrl: 'partials/partials.html', controller: 'Myctrl1' });
$routeProvider.when('/view2', { templateUrl: 'partials/partials1.html', controller: 'Myctrl2' });
$routeProvider.otherwise({ redirectTo: '/view1' });
}]);
try this

AngularJS - Injecting a Provider

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) {

Categories

Resources