AngularJS路由配置未达预期,报$injector:modulerr模块错误
我来帮你排查这个$injector:modulerr错误,让你的ng-view正常加载Views/post.html视图。这个错误本质是AngularJS无法正确初始化你的模块,大概率是以下几个环节出了问题,咱们逐个解决:
1. 未正确引入ngRoute模块的独立脚本
AngularJS的ngRoute不属于核心模块,必须单独引入对应版本的脚本文件,而且要放在AngularJS核心脚本之后。比如:<!-- 先引入AngularJS核心 --> <script src="angular.min.js"></script> <!-- 再引入同版本的ngRoute脚本 --> <script src="angular-route.min.js"></script>注意:核心脚本和ngRoute脚本的版本必须一致,否则会出现兼容性问题。
2. 路由配置缺少根路径("/")的映射,且otherwise重定向目标无效
你当前的路由只配置了/index路径,但otherwise会把未匹配的路径重定向到/,而这个路径没有对应的路由规则,导致加载失败。你有两种修复方式:
方案一:修改otherwise的重定向目标为已配置的/indexangular.module('app', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when("/index", { templateUrl: "Views/post.html" }) .otherwise({ redirectTo:"/index" }) // 改为已存在的路由 })方案二:给根路径
/也配置对应的视图angular.module('app', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when("/", { templateUrl: "Views/post.html" }) // 新增根路径路由 .when("/index", { templateUrl: "Views/post.html" }) .otherwise({ redirectTo:"/" }) })3. 访问URL的路由格式不符合默认规则
AngularJS默认使用哈希模式(Hash Mode)处理路由,所以你访问的URL应该是http://localhost:55657/index.html#/index,而不是直接访问index.html。如果想去掉URL中的#,可以开启HTML5模式,步骤如下:- 在路由配置中注入
$locationProvider并开启HTML5模式:angular.module('app', ['ngRoute']) .config(function ($routeProvider, $locationProvider) { $routeProvider .when("/index", { templateUrl: "Views/post.html" }) .otherwise({ redirectTo:"/index" }); // 开启HTML5模式 $locationProvider.html5Mode(true); }) - 在
index.html的<head>标签中添加<base href="/">,确保路由路径正确解析。
- 在路由配置中注入
4. 页面未正确指定ng-app模块
检查你的index.html是否在<body>或父元素上添加了ng-app="app"指令,这是AngularJS识别并初始化模块的关键:<body ng-app="app"> <!-- 必须指定你的模块名 --> <div class="container"> <ng-view></ng-view> </div> </body>
按照以上步骤逐一排查,应该就能解决模块加载错误和视图无法显示的问题了。
内容的提问来源于stack exchange,提问作者Sanjalee Patni




