AngularJS单页应用ng-view不显示数据且控制台无报错如何排查
问题排查与修正方案
1. 依赖版本不匹配
你使用的AngularJS核心版本是1.6.9,但ngRoute模块版本是1.2.28,二者版本不兼容会导致路由功能异常。需要将ngRoute的版本替换为和核心库一致的1.6.9版本,替换主页面中对应的引入代码:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.min.js"></script>
2. 路由配置路径缺少前置斜杠
$routeProvider的when方法第一个参数需要加前置/才能匹配链接里的路由路径,你当前写的when('First')无法匹配#/First的路由,同时Angular 1.6+默认开启了hash前缀!,需要额外配置适配你的链接写法,修正后的控制器路由配置如下:
var RouteApp = angular.module('RouteApp', ['ngRoute']); RouteApp.config(function ($routeProvider, $locationProvider) { // 关闭Angular 1.6+默认的hash前缀!,适配你当前的链接写法 $locationProvider.hashPrefix(''); $routeProvider.when('/First', { templateUrl: 'First.html', controller : 'CtrFive' }) .when('/Second', { templateUrl: 'Second.html', controller: 'CtrSix' }) // 可选配置:访问根路径时自动跳转到First页 .otherwise({ redirectTo: '/First' }) }); RouteApp.controller('CtrFive', ['$scope', function ($scope) { }]); RouteApp.controller('CtrSix', ['$scope', function ($scope) { }]);
3. 子页面冗余标签可移除
First.html和Second.html作为嵌入视图,不需要完整的HTML文档结构,只保留内容部分即可,避免嵌套html/head/body标签产生冲突:
First.html修正后:
<h1>This is first!</h1>
Second.html修正后:
<h1>This is second!</h1>
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

