目录结构
代码
root.html
<!DOCTYPE html>
<html lang="zh" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS</title>
<script type="text/javascript" src="angular/1.7.2/angular.js"></script>
<script type="text/javascript" src="angular/1.7.2/angular-route.js"></script>
</head>
<body>
<div ng-controller="myCtrl">
<ul>
<li><a href="#/a">click a</a></li>
<li><a href="#/b">click b</a></li>
</ul>
<div ng-view ></div><!--这里就是渲染其他视图的地方-->
</div>
<script type="text/javascript">
angular.module("myApp",["ngRoute"])
.controller("aController",function($scope,$route){
$scope.hello = "hello,I'm a!";
})
.controller("bController",function($scope){
$scope.hello = "hello,I'm b!";
})
.controller("myCtrl",function($scope,$location){
$scope.$on("$viewContentLoaded",function(){ //当新的URL加载完成后,通知myCtrl
console.log("ng-view content loaded!");
});
$scope.$on("$routeChangeStart",function(event,next,current){ //当URL发生改变时,通知myCtrl
//event.preventDefault(); //cancel url change
console.log("route change start!");
});
})
.config(function($routeProvider) {
$routeProvider
.when('/a', {
templateUrl: 'view/a.html',
controller: 'aController'
})
.when('/b', {
templateUrl: 'view/b.html',
controller: 'bController',
resolve: {
// 延迟 1秒再跳转
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 3000);
return delay.promise;
}
}
})
.otherwise({
redirectTo: '/'
});
});
</script>
</body>
</html>
a.html
<div><h1>a:{{hello}}</h1></div>
b.html
<div><h1>b:{{hello}}</h1></div>
效果演示
注意事项
- 引入angular.js文件必须是在引入angular-route.js文件之前
- 页面设置
<div ng-view ></div><!--这里就是渲染其他视图的地方,即展示跳转的模版内容-->
- 浏览器本地跨域:Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension
- 跳转文件的时候请求路径“/”变”%2F”,导致跳转失败,需要加入下面代码
testModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);