AngularJS路由功能失效求助:其他功能正常,已用CDN
AngularJS路由失效问题排查与修复
问题根源梳理
- 无默认路由规则:未配置
otherwise,初始页面或访问未定义路由时无匹配项,导致路由无响应 - 模板重复声明控制器:路由配置中已指定
controller,模板内又添加ng-controller会重复实例化控制器,引发逻辑冲突 - 缺失关键控制器/服务定义:
/dataBinding路由依赖的myCtrl控制器、customeServiceCtrl依赖的myService服务均未实现 - 无效路由链接:页面中
#/list链接无对应路由配置,点击后会跳转至未定义路径
修正后的完整代码
HTML部分
<div ng-app="myApp"> <a href="#/dataBinding">Data Binding</a> <a href="#/dataBinding">List</a> <!-- 若需独立List页面,可在路由中新增对应配置 --> <a href="#/httpapi">$https API</a> <a href="#/cusService">Custom Service API call</a> </div> <div ng-view></div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
JavaScript部分
var app = angular.module('myApp', ['ngRoute']); app.config(function($routeProvider){ $routeProvider .when('/dataBinding', { template: ` <h3>Data Binding controller</h3> <input type="text" ng-model="firstName"> <input type="text" ng-model="lastName"> <br><br> {{ firstName + ' ' + lastName }} `, controller: 'myCtrl' }) .when('/httpapi', { template: ` <h3>$https API Controller</h3> <p>A fact From API: {{ reqCode }}</p> `, controller: 'apiCtrl' }) .when('/cusService', { template: ` <h3>Custom Service API call Controller</h3> <p>Genderize API using Custom Service: {{ cusserviceData }}</p> `, controller: 'customeServiceCtrl' }) .otherwise({ redirectTo: '/dataBinding' }); // 添加默认路由,确保页面初始加载有内容 }) // 补充缺失的myCtrl控制器 app.controller('myCtrl', function($scope) { $scope.firstName = ''; $scope.lastName = ''; }) app.controller('apiCtrl',function($scope,$http){ $http({ method:'get', url:'https://catfact.ninja/fact' }).then(function(response){ $scope.reqCode = response.data.fact; }) }) // 补充缺失的myService服务定义 app.service('myService', function($http) { this.resData = function(data) { return $http.post('https://api.genderize.io/', data) .then(function(response) { return response.data; }); }; }) app.controller('customeServiceCtrl',function($scope,myService){ $scope.myData = {"email": "eve.holt@reqres.in","password": "cityslicka"}; myService.resData($scope.myData).then(function(token) { $scope.cusserviceData = token; }) })
核心修正说明
- 添加
otherwise默认路由,确保初始加载和无效路由请求都能跳转到已定义的有效页面 - 删除模板内的
ng-controller声明,避免控制器重复实例化导致的异常 - 补全
myCtrl控制器和myService服务的定义,解决依赖缺失问题 - 修正无效的
#/list链接(若需保留独立List功能,可在路由配置中新增/list规则)
内容的提问来源于stack exchange,提问作者Arun
相关产品推荐
相关产品推荐

