AngularJS之页面跳转Route

  • AngularJS下载
  • 关于AngularJS路由的介绍及其属性

目录结构

AngularJS之页面跳转Route_第1张图片

代码

root.html


<html lang="zh" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJStitle>
    <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 aa>li>
            <li><a href="#/b">click ba>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>

效果演示

AngularJS之页面跳转Route_第2张图片

注意事项

  1. 引入angular.js文件必须是在引入angular-route.js文件之前
  2. 页面设置
  3. 浏览器本地跨域:Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension
  4. 跳转文件的时候请求路径“/”变”%2F”,导致跳转失败,需要加入下面代码
testModule.config(['$locationProvider', function($locationProvider) {
     $locationProvider.hashPrefix('');
}]);

参考

  • 关于AngularJS路由的介绍及其属性
  • 关于Angularjs版本不得不说的问题(追加部分),“/”变”%2F”问题

你可能感兴趣的:(Angular)