首页 > 代码库 > Angular-1.6 路由 简单使用

Angular-1.6 路由 简单使用

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body ng-app="app">
<div ng-controller="MainController">
    Choose:
    <a href="#/Book/Moby">Moby</a> |
    <a href="Book/Moby/ch/1">Moby: Ch1</a> |
    <a href="Book/Gatsby">Gatsby</a> |
    <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
    <a href="Book/Scarlet">Scarlet Letter</a><br/>

    <div ng-view></div>

    <hr />

    <pre>$location.path() = {{$location.path()}}</pre>
    <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
    <pre>$route.current.params = {{$route.current.params}}</pre>
    <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
    <pre>$routeParams = {{$routeParams}}</pre>
</div>


<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>

<script>

    var app = angular.module(app,[ngRoute]);
    //注册控制器
    app.controller(MainController,[$scope,$route,$routeParams,$location,
        function ($scope,$route,$routeParams,$location) {
            $scope.$route=$route;
            $scope.$routeParams=$routeParams;
            $scope.$location=$location;
        }
    ]).controller(BookController,[$scope,$routeParams,function ($scope,$routeParams) {
        $scope.name= BookController;
        $scope.$routeParams= $routeParams;
    }]).config([$routeProvider,$locationProvider,function ($routeProvider, $locationProvider) {
        //这是因为Angular 1.6 版本更新后 对路由做的处理,这样才可以和以前版本一样正常使用
        $locationProvider.hashPrefix(‘‘);

        $routeProvider.when(/Book/:bookId,{//:bookId作为路由参数使用
            templateUrl:app/templates/book.html,
            controller:BookController//该路由匹配后使用的默认控制器,页面上就不用单独再配置
        });
    }]);
</script>

</body>
</html>

book.html:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <div>
 9         <p>{{name}}</p>
10         <p>{{$routeParams}}</p>
11         <p>{{$routeParams.bookId}}</p>
12     </div>
13 
14 </body>
15 </html>

  注意:

 $locationProvider.hashPrefix(‘‘);  //这是因为Angular 1.6 版本更新后 对路由做的处理,这样才可以和以前版本一样正常使用
       

 

Angular-1.6 路由 简单使用