javascript AngularJS routeprovider注入错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21098693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:03:19  来源:igfitidea点击:

AngularJS routeprovider injection error

javascripthtmlangularjs

提问by Dirk

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

我正在学习 AngularJS,我现在正在尝试$routeProvider,但我无法让它工作。

index.html:

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:

view.html

<p>Hello World!</p>

controllers.js:

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?

我该如何解决这个问题?

回答by KayakDave

Change .otherwhiseto .otherwise.

更改.otherwhise.otherwise

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

遇到这些问题时,一个好的做法是尝试未缩小版本的 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'

未捕获的错误:[$injector:modulerr] 无法实例化模块应用程序,原因是:类型错误:对象 # 没有方法“其他”

回答by Twisha Desai

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

解决方案:在你的路由配置上创建一个 $inject 属性,如下所示:

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.

当 js 被缩小时,AngularJS 现在将能够成功注入 $routeProvider。