AngularJS之页面跳转Route

目录结构

这里写图片描述

代码

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>

效果演示

这里写图片描述

注意事项

  1. 引入angular.js文件必须是在引入angular-route.js文件之前
  2. 页面设置<div ng-view ></div><!--这里就是渲染其他视图的地方,即展示跳转的模版内容-->
  3. 浏览器本地跨域:Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension
  4. 跳转文件的时候请求路径“/”变”%2F”,导致跳转失败,需要加入下面代码
testModule.config(['$locationProvider', function($locationProvider) {
     $locationProvider.hashPrefix('');
}]);

参考

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值