Angular: 'modulerr', "Failed to instantiate module - javascript

I'm trying to learn Angular and hitting a brick wall trying to add routes to my application.
I keep getting presented this error
'modulerr', "Failed to instantiate module
From other stackoverflow questions i gather its not from loading ngRoute correctly but angular-route.js is loaded in the head, and ngRoute is declared in my module construct so i'm a bit confused
My index file is as followed
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.js"></script>
<script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.1.2/angularfire.min.js"></script>
<script src="js/app.js"></script>
<script src="js/animations.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="pgpChatApp">
<div class="view-container">
<div ng-view="" class="view-frame"></div>
</div>
</body>
</html>
My app file
'use strict';
var pgpChatApp = angular.module('pgpChatApp', [
'ngRoute',
'firebase',
'pgpChatAnimations',
'pgpChatControllers',
'pgpChatFilters',
'pgpChatServices'
]);
pgpChatApp.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when("/home", {
// the rest is the same for ui-router and ngRoute...
controller: "userAuth",
templateUrl: "partials/home.html"
}).when("/account", {
// the rest is the same for ui-router and ngRoute...
controller: "AccountCtrl",
templateUrl: "partials/msg_room.html",
resolve: {
// controller will not be loaded until $requireAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
"currentAuth": ["Auth", function (Auth) {
// $requireAuth returns a promise so the resolve waits for it to complete
// If the promise is rejected, it will throw a $stateChangeError (see above)
return Auth.$requireAuth();
}]
}
});
}]);
My controller file
var pgpChatAppControllers = angular.module('pgpChatAppControllers', []);
pgpChatAppControllers.controller("userAuth", ["$scope", "$routeParams", "Auth",
function ($scope, $routeParams, Auth) {
$scope.createUser = function () {
$scope.message = null;
$scope.error = null;
Auth.$createUser({
email: $scope.email,
password: $scope.password
}).then(function (userData) {
$scope.message = "User created with uid: " + userData.uid;
}).catch(function (error) {
$scope.error = error;
});
};
$scope.removeUser = function () {
$scope.message = null;
$scope.error = null;
Auth.$removeUser({
email: $scope.email,
password: $scope.password
}).then(function () {
$scope.message = "User removed";
}).catch(function (error) {
$scope.error = error;
});
};
}]);
Has anyone got an idea what the fix is?
Thanks in advanced
[EDIT]
Full exception message
http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=pgpChatAnimations&p1=Error: [$injector:nomod] http://errors.angularjs.org/1.3.15/$injector/nomod?p0=pgpChatAnimations
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:6:417
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:21:412
at a (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:21:53)
at w.bootstrap (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:21:296)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:35:116
at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:7:302)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:34:399)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:35:63
at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:7:302)"

The url for angular-route is not working. Try using:
http://code.angularjs.org/1.2.0-rc.3/angular-route.js

I guess i my module names still weren't matching the defined modules in app.js
This diff shows the fix
https://github.com/jkirkby91/angular-firebase-chat/commit/35be74592197d16435adb322f0e24963108ed97a

Related

Adding factory getting Error: [$injector:unpr]

Trying to add a simple factory and getting error:
Error: [$injector:unpr] http://errors.angularjs.org/1.4.6/$injector/unpr?p0=subfactoryProvider%20%3C-%20subfactory%20%3C-%20authService%20%3C-%20AuthorizationInterceptor%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24compile
I have added a script tag:
<script src="app/subfactory.js"></script>
The subfactory is defined as follows:
(function () {
//'use strict';
angular
.module('app')
.factory('subfactory', subfactory);
function subfactory() {
var subValue = {};
return {
set: set,
get: get
};
function get() {
return subValue;
}
function set(value) {
subValue = value;
}
}
});
It is used in authService:
(function () {
//'use strict';
angular
.module('app')
.factory('authService', authService);
authService.$inject = ['subfactory'];
function authService(subfactory) {
// removed code for brevity
mgr.getUser().then(function (user) {
if (user) {
var idToken = user.id_token;
var dataIdToken = getDataFromToken(idToken);
subfactory.set(dataIdToken.sub);
} else {
//console.log("User not logged in");
}
});
I also have AuthorizationInterceptor that calls authService:
app.factory("AuthorizationInterceptor", ['$q', '$injector', '$rootScope', '$window', 'authService', function ($q, $injector, $rootScope, $window, authService) {
Please, How can I resolve this error?
Edit:
<script src="app/app.js"></script>
<script src="app/authService.js"></script>
<script src="app/subfactory.js"></script>
app.factory("AuthorizationInterceptor"... is defined in app.js
The error message is the only message in the F12 console.
Try flipping the order of your declaration files like follows :
// only define your module here
<script src="app/app.js"></script>
// define your factories
<script src="app/subfactory.js"></script>
<script src="app/authService.js"></script>
// define your authorization factory here just like the previous two
<script src="app/Authorization.js"></script>
Can not add it as comment. So adding an answer here. You need to change the order of file declaration . In your case error is because you have authService.js before subfactory.js. authService.js searches for its dependency and do not find it as subfactory.js yet not added.
<script src="app/app.js"></script>// If it main file whre angular module is created
<script src="app/subfactory.js"></script>
<script src="app/authService.js"></script>

how to write test case for a controller in angularJS using jasmine

I have a angular module in a separate file
userModule.js
'use strict';
angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop','ngFileUpload'])
.run(function ($rootScope, $location, $http) {
$http.get('/token')
.success(function (user, status) {
if (user) {
$rootScope.user = user;
}
});
})
I've a controller in a separate another file which uses this module:
userController.js
'use strict';
var usersApp = angular.module('users');
usersApp.controller('usersControllerMain', ['$scope', '$http', '$routeParams','$location', 'growl','$rootScope','$mdDialog','API',
function($scope, $http, $routeParams, $location,growl,$rootScope,$mdDialog,API) {
$scope.action = "none";
$scope.password = '',
$scope.grade = function() {
var size = $scope.password.length;
if (size > 8) {
$scope.strength = 'strong';
} else if (size > 3) {
$scope.strength = 'medium';
} else {
$scope.strength = 'weak';
}
};
i've some dependencies defined in my controller for other uses.
Now i need to test this controller. SO i've written a spec file which i'll run directly in browser. I dont want to use test runners like karma:
jasmine.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.8/angular-mocks.js"></script>
<script type="text/javascript">
describe('userControllerMain testing', function(){
beforeEach(angular.mock.module('users'));
var $controller;
beforeEach(angular.mock.inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.grade', function() {
it('sets the strength to "strong" if the password length is >8 chars', function() {
var $scope = {};
var controller = $controller('usersControllerMain', { $scope: $scope });
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
});
});
</script>
</head>
<body>
</body>
</html>
i took this example from angular docs.
but when i run my jasmine.html in browser it throwing an injector module error as shown below:
. am i doing anything wrong here..??
There's something seriously wrong with the approach that you're following here. You should be mocking the controller inside a beforeEach block rather than an it block.
So this is how your test file should be:
describe('userControllerMain testing', function(){
beforeEach(module('users'));
beforeEach(inject(function($controller, $rootScope) {
$scope = $rootScope.$new();
usersControllerMain = $controller('usersControllerMain', {
$scope: $scope
});
}));
describe('$scope.grade', function() {
it('sets the strength to "strong" if the password length is >8 chars', function() {
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
});
});
Hope this helps.

Error: [$injector:modulerr] with angular JS [GULP CONTEXT]

first of all , i know this error seems to be famous and i should be able to get the solution with google easily but unfortunately none of the links i read did help me to solve the problem...
I underline the fact i use gulp to minify the Javascript.
Basically this is my module:
(function () {
var app = angular.module('meanApp', ['ngRoute']);
app.config (function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home/home.view.html',
controller: 'homeCtrl',
controllerAs: 'vm'
})
.when('/register', {
templateUrl: '/auth/register/register.view.html',
controller: 'registerCtrl',
controllerAs: 'vm'
})
.when('/login', {
templateUrl: '/auth/login/login.view.html',
controller: 'loginCtrl',
controllerAs: 'vm'
})
.when('/profile', {
templateUrl: '/profile/profile.view.html',
controller: 'profileCtrl',
controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
app.run(function($rootScope, $location, authentication) {
$rootScope.$on('$routeChangeStart', function(event, nextRoute, currentRoute) {
if ($location.path() === '/profile' && !authentication.isLoggedIn()) {
$location.path('/');
}
});
});
})();
authentication is the following service:
(function () {
angular
.module('meanApp')
.factory('authentication', authentication);
// $inject : To allow the minifiers to rename the function parameters and still be able to inject the right services, the function needs to be annotated with the $inject property. The $inject property is an array of service names to inject.
// https://docs.angularjs.org/guide/di
authentication.$inject = ['$http', '$window'];
function authentication ($http, $window) {
var saveToken = function (token) {
$window.localStorage['mean-token'] = token;
};
var getToken = function () {
return $window.localStorage['mean-token'];
};
var isLoggedIn = function() {
var token = getToken();
var payload;
if(token){
payload = token.split('.')[1];
payload = $window.atob(payload); //will decode a Base64 string
payload = JSON.parse(payload);
return payload.exp > Date.now() / 1000;
} else {
return false;
}
};
var currentUser = function() {
if(isLoggedIn()){
var token = getToken();
var payload = token.split('.')[1];
payload = $window.atob(payload);
payload = JSON.parse(payload);
return {
email : payload.email,
name : payload.name
};
}
};
//An interface between the Angular app and the API, to call the login and register end-points and save the returned token. This will use the Angular $http service
// strict mode :
var register = function(user) {
console.log("ARNAUD: Arriving in register promise");
return $http.post('/api/register', user).success(function(data){
saveToken(data.token);
});
};
var login = function(user) {
return $http.post('/api/login', user).success(function(data) {
saveToken(data.token);
});
};
var logout = function() {
$window.localStorage.removeItem('mean-token');
};
/* console.log("currentUser:"+currentUser);
console.log("saveToken:"+saveToken);
console.log("getToken:"+getToken);
console.log("isLoggedIn:"+isLoggedIn);
console.log("register:"+register);
console.log("login:"+login);
console.log("logout:"+logout);*/
return {
currentUser : currentUser,
saveToken : saveToken,
getToken : getToken,
isLoggedIn : isLoggedIn,
register : register,
login : login,
logout : logout
};
}
})();
A controller:
(function () {
angular
.module('meanApp')
.controller('registerCtrl', registerCtrl);
registerCtrl.$inject = ['$location', 'authentication'];
function registerCtrl($location, authentication) {
console.log("ARNAUD : inside registerCtrl, initializing the properties to empty");
var vm = this;
vm.credentials = {
name : "",
email : "",
password : ""
};
vm.onSubmit = function () {
console.log('ARNAUD : arriving in vm.Submit');
authentication
.register(vm.credentials)
.error(function(err){
alert(err);
})
.then(function(){
$location.path('profile');
});
};
}
})();
my index.html:
<!DOCTYPE html>
<html ng-app="meanApp">
<head>
<title>MEAN stack authentication example</title>
<base href="/">
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap-theme.min.css">
</head>
<body ng-view>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="app.min.js"></script>
</body>
</html>
Thanks a lot for your help
You missed to have to follow minification rule applies to DI on config & run block which should be like below. I'd suggest you to follow Inline Array Annotation method of DI which injecting dependency.
Code
(function () {
var app = angular.module('meanApp', ['ngRoute']);
app.config (['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
//code as is
}
]);
app.run(['$rootScope', '$location', 'authentication',
function($rootScope, $location, authentication) {
//code as is
}
]);
})();
See the warning specified here in DOCS

My Basic Angular App failing me when i'm designing my First Mean stack UI

app.js
var myApp = angular.module('myApp',[]);
myApp.controller('mainCtrl',function($scope){
$scope.name="vignesh";
});
I'm doing a basic app building with MEAN Stack, for most of the parts we use Node API's to connect with MongoDB and user authentication,I'm done with my authentication part in Node.js but while designing routing UI I'm facing this issue
HTML
<!DOCTYPE>
<html ng-app="myApp">
<head>
<title>User Story</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-route.js"></script>
</head>
<body>
<div ng-controller="mainCtrl">{{name}}</div>
<script type="text/javascript" src="/service/authService.js"></script>
<script type="text/javascript" src="/controllers/controllers.js"></script>
<script type="text/javascript" src="/app.js"></script>
</body>
</html>
angular.module('authService',[])
.factory('Auth',function($http,$q,AuthToken){
var authFactory={};
authFactory.login=function(username,password){
return $http.post('/app/login',{
username:username,
password:password
}). sucess(function(data){
AuthToken.setToken(data.token);
return data;
})
}
authFactory.logout=function(){
AuthToken.setToken();
}
authFactory.isLoggedin=function(){
if(AuthToken.getToken())
return true;
else
return false;
}
authFactory.getUser=function(){
if(AuthToken.getToken())
return $http.get('/api/me');
else
return $q.reject({message:"user has no token set"});
}
return authFactory;
})
. factory('AuthToken', function($window){
var authTokenFactory={};
authTokenFactory.getToken=function(){
return $window.localStorage.getItem('token');
}
authTokenFactory.setToken=function(token){
if(token)
$window.localStorage.setItem('token',token);
else
$window.localStorage.removeeItem('token');
}
return authTokenFactory;
})
.factory('AuthInterceptor',function($q,$location,AuthToken){
var interceptorFactory={};
interceptorFactory.request=function(config){
var token=AuthToken.getToken();
if(token){
config.header['x-access-token']=token;
}
return config;
};
interceptorFactory.responseError=function(response){
if(response.status==403)
$location.path('/login');
return $q.reject(response);
}
})
controllers.js
angular.module('mainCtrl', [])
.controller('MainController', function($rootScope,$location,Auth){
var vm = this;
vm.loggedIn = Auth.isLogged();
$rootScope.$on('$routechangeStart',function () {
vm.loggedIn=Auth.isLogged();
Auth.getUser().then(function(data){
vm.user=data.data;
});
});
vm.doLogin= function(){
vm.processing=true;
vm.error='';
Auth.login(vm.loginData.username, vm.loginData.password)
.sucess(function (data) {
// body...
vm.user=data.data;
});
if(data.success)
$location.path('/');
else
vm.erroe=data.message;
}
vm.doLogout=function(){
Auth.logout();
$location.path('/logout');
}
})
error says:
Uncaught SyntaxError: Unexpected token
Uncaught Error: [$injector:modulerr] Failed to instantiate module
myApp due to: Error: [$injector:nomod] Module 'myApp' 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.
You need to initialize you app module correctly.
var myApp = angular.module('myApp', []);
Working Plunkr
Update
As you have different module per each JS file, you need to combine them while using any provider/service that module, As in your case you have used Auth service but the authService module has not injected.
Controllers.js
angular.module('mainCtrl', ['authService']) //injected authService module
.controller('MainController', function($rootScope,$location,Auth){
App.js
var myApp = angular.module('myApp',['mainCtrl']);
myApp.controller('mainCtrl',function($scope){

How to handle nested services and promises using resolve and $routeChangeError

That's more like a research I did while I was playing with AngularJS and I would like to share as I think some people might find this useful.
Sometimes you need to fetch some data from several services before you instantiate the controller and render the view.
You could also have a situation when a particular service is waiting for a response from another service - kinda of nested service structure.
On top of that you want to make sure that if any of these services fails you will handle the error accordingly.
The module myApp has to services called myFirstService and mySecondService.
If you make any of the services fail by rejecting it:
defer.reject("second Service Failed");
The $routeChangeError event is fired and a message is displayed to the user in the console.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>myApp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"> </script>
<script>
var myApp = angular.module('myApp', []);
myApp.config(function($routeProvider){
$routeProvider
.when('/',
{
controller: 'ViewCtrl',
templateUrl: 'view/app.html',
resolve: {
loadData: function(myFirstService){
return myFirstService.start();
}
}
})
});
var appCtrl = myApp.controller('AppCtrl', function($scope, $rootScope){
$rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
console.log('Some service has failed: ', rejection);
});
});
var viewCtrl = myApp.controller('ViewCtrl', function($scope, $route){
$scope.feedback = {
message: 'All the services are working!'
}
});
myApp.factory('myFirstService', ['$q', '$timeout','mySecondService', function($q, $timeout, mySecondService) {
var defer = $q.defer();
return {
start: function() {
$timeout(function(){
defer.resolve('FIRST Service \'myFirstService\' Failed');
}, 2000);
return mySecondService.start().then(function(){
return defer.promise
});
}
}
}]);
myApp.factory('mySecondService', ['$q', '$timeout', function($q, $timeout) {
var defer = $q.defer();
return {
start: function() {
$timeout(function(){
defer.resolve("second Service Failed");
}, 2000);
return defer.promise;
}
}
}]);
</script>
</head>
<body ng-app="myApp" ng-controller="AppCtrl">
<script id="view/app.html" type="text/ng-template">
<h1>{{ feedback.message }}</h1>
</script>
<div ng-view></div>
</body>
</html>

Categories