JohnWick
JohnWick

Reputation: 5149

AngularJS - Uncaught Error: [$injector:modulerr] Failed to instantiate module

I am learning Angular and have am receiving the cryptic and mysterious "AngularJS - Uncaught Error: [$injector:modulerr]" in my console when viewing index.html, which I will post below (as well as the Angular JS files being referenced.)

Can someone please tell me what I'm doing wrong? The error message is so vague...

index.html

<!DOCTYPE html>
<html lang="en">
<head>

    <meta char-set="UTF-8">
    <!--FOR ANGULAR ROUTING-->
    <base href="/">
    <link rel="stylesheet" href="assets/css/style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-animate.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-route.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-resource.min.js"></script>

    <script src="app/controllers/mainCtrl.js"></script>
    <script src="app/services/authService.js"></script>

    <script src="app/app.routes.js"></script>
    <script src="app/app.js"></script>

</head>

<body ng-app="userApp" ng-controller="mainController as main">

    <header>
        <ul>
            <li ng-if="!main.loggedIn">
                <a href="/login">Login!</a>
            </li>

            <li ng-if="main.loggedIn">
                Hello, {{main.user.name}}
            </li>

            <li ng-if="main.loggedIn">
                <a href="#" ng-click="main.doLogout()">Logout</a>
            </li>
        </ul>
    </header>

    <main>
        <div ng-view></div>
    </main>

</body>
</html>

app.js

angular.module('userApp', [
'app.routes',
'authService',
'mainCtrl'
]);

app.routes.js

angular.module('app.routes', ['ngRoute'])

.config(function($routeProvider, $locationProvider) {

    $routeProvider
    .when('/', {
        templateUrl: 'app/views/pages/home.html'
    })

    .when('/login', {
        templateUrl: 'app/views/pages/login.html',
        controller: 'mainController',
        controllerAs: 'login'
    });

    $locationProvider.html5mode(true);
});

authService.js

angular.module('authService', ['ngStorage'])

.factory('Auth', function($http, AuthToken) {

var authFactory = {};

//Login
authFactory.login = function(username, password) {
    return $http.post('/login', {
        username: username,
        password: password
    })
    .success(function(data){
        AuthToken.setToken(data.token);
        return data;
    });
};

//Logout
authFactory.logout = function() {
    AuthToken.setToken();
};

//Check if user is logged in.
authFactory.isLoggedIn = function() {
    if (AuthToken.getToken())
        return true
    else
        return false
};

authFactory.getUser = function() {

    if (AuthToken.getToken())
        return $http.get('/api/users/me', { cache: true });
    else
        return $q.reject({ message: 'User has no token' });
};

return authFactory;

})

.factory('AuthToken', function($window) {

var authTokenFactory = {};

//Get auth token
authTokenFactory.getToken = function() {
    return $window.localStorage.getItem('token');
};

//Set or clear auth token
authTokenFactory.setToken = function(token) {
    if (token) {
        $window.localStorage.setItem('token', token);
    };
};

return authTokenFactory;

})

.factory('AuthInterceptor', function($q, $location, Auth) {

    //Add token to all requests.

    var authInterceptorFactory = {};

    authInterceptorFactory.request = function(config) {

        var token = Auth.getToken();

        if (token) {
            config.headers['x-access-token'] = token;
        };

        return config;

    };

    authInterceptorFactory.responseError = function(response) {

        if (response.status == 403) {
            AuthToken.setToken();
            $location.path('/login');
        };

        return $q.reject(response);
    };

    return authInterceptorFactory;

});

mainCtrl.js

angular.module('mainCtrl', [])

 .controller('mainController', function($rootScope, $location, Auth) {

   var vm = this;

   // get info if a person is logged in
   vm.loggedIn = Auth.isLoggedIn();

   // check to see if a user is logged in on every request
   $rootScope.$on('$routeChangeStart', function() {
     vm.loggedIn = Auth.isLoggedIn();

     // get user information on route change
     Auth.getUser()
       .success(function(data) {
         vm.user = data;
       });
   });  

   // function to handle login form
   vm.doLogin = function() {

     // call the Auth.login() function
     Auth.login(vm.loginData.username, vm.loginData.password)
       .success(function(data) {

         // if a user successfully logs in, redirect to users page
         $location.path('/users');
       });
   };

   // function to handle logging out
   vm.doLogout = function() {
     Auth.logout();
     // reset all user info
     vm.user = {};
     $location.path('/login');
   };

 });

Upvotes: 2

Views: 2983

Answers (3)

Math
Math

Reputation: 818

I has this error, migrating to 1.4.x angular, and in my case, using the min version, the exception didn't say anything than

Uncaught Error: [$injector:modulerr] Failed to instantiate module mymodule

using the non minified version, I see an inner error that was a module that start in upper case

Uncaught Error: [$injector:modulerr] Failed to instantiate module mymodule due to: Error: [$injector:modulerr] Failed to instantiate module aon.module.directives due to: Error: [$compile:baddir] Directive name 'Lists-Radio' is invalid. The first character must be a lowercase letter

renaming to list-Radio was solved.

in your case, probably

factory('Auth' ...

Hope it works

Upvotes: 1

JohnWick
JohnWick

Reputation: 5149

So, after fiddling around, I tried an earlier version of angular from a CDN. The older version gave a much more detailed error message in my console, and told me that in app.routes.js, html5mode is not a function. Woops. Changing

$locationProvider.html5mode(true);

to this

$locationProvider.html5mode = true;

fixed the problem. Wish the newest version of Angular that I was using would have just told me that, but oh well.

Upvotes: 0

keithm
keithm

Reputation: 958

You are using ngStorage but you don't seem to be pulling in the js file for that module. It is not part of Angular core so you need to reference the js file for ngStorage in your index.html file.

Out of interest - is there any reason you create a module for your service / controller instead of having them as part of your main 'userApp' module ?

Upvotes: 1

Related Questions