简体   繁体   中英

AngularJS routeprovider injection error

I'm learning AngularJS, and I'm now trying the $routeProvider , but I can't get it to work.

index.html :

<!DOCTYPE html>

<html ng-app="App">
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular-route.min.js"></script>
        <script type="text/javascript" src="scripts/controllers.js"></script>
    </head>
    <body>
        <div ng-view></div>
    </body>
</html>

view.html :

<p>Hello World!</p>

controllers.js :

var app = angular.module('App', ['ngRoute']);

app.config(
    function($routeProvider){
        $routeProvider.when("/something",{
            templateUrl: "view.html",
            controller: "MyController"
        })
        .otherwhise({
            redirectTo: "/"
        });
    }
);

function MyController($scope){

}

Whenever I run this, I get an error message that says

Uncaught Error: [$injector:modulerr]

How can I solve this?

Change .otherwhise to .otherwise .

A good practice when you run into these issues is to try the un-minified version of Angular.

The un-minified error is much more helpful:

Uncaught Error: [$injector:modulerr] Failed to instantiate module App due to: TypeError: Object # has no method 'otherwhise'

Solution: Create a $inject property on your route config as follows: -

var app = angular.module('App', ['ngRoute']);

(function (app) {
    var routeConfig = function($routeProvider){
        $routeProvider.when("/something",{
            templateUrl: "view.html",
            controller: "MyController"
        })
        .otherwhise({
            redirectTo: "/"
        });
    };
    routeConfig.$inject = ['$routeProvider'];
    app.config(routeConfig);
})(angular.module("App"));

AngularJS will now be able to inject $routeProvider successfully when js is minified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM