Angular-1.6 路由 簡單使用

index.htmlhtml

<!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:app

 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>

  注意:ide

 $locationProvider.hashPrefix('');  //這是由於Angular 1.6 版本更新後 對路由作的處理,這樣才能夠和之前版本同樣正常使用
相關文章
相關標籤/搜索