跳到主要內容

Router and Multiple Views

  • Router and Multiple Views 介紹
    在angularJS提供一個很強大的功能叫作路由(router),主要應用在切換不同model和views,更容易做出SPA( Single Page Application)註一等級的產品。本章我們介紹如何利用ngRoute的模組切換不同的網頁視圖。
註一: SPA 的概念傳統的 HTML 網頁一樣,需要每做一個動作就整個更新網頁,但是SAP希望可以像視窗軟體一樣,只需要變更顯示的內容而不需更新整個網頁。
  • 載入路由功能
    <head>
         <script src="angular.js" />
        <script src="angular-route.js"/></head>
  • 定義路徑與規畫控制器
    我們利用$routeProvider來切換網頁內容,下列範例定/home, /viewItems
    兩個畫面規畫。在mainApp.controller控制器來切換/home, /viewItems的
    之內容。


    itemController.js
    var mainApp = angular.module("mainApp", ['ngRoute']);

    mainApp.config(function($routeProvider) {
       $routeProvider
            .when('/home', {
                templateUrl: 'home.html',
                controller: 'ItemController'
            })
            .when('/viewItems', {
                templateUrl: 'viewItems.html',
                controller: 'ItemController'
            })
            .otherwise({
                redirectTo: '/home'
            });
    });

    mainApp.controller('ItemController', function($scope) {
        $scope.items = [
            {name: 'apple', city:'New York'},
            {name: 'banana', city:'London'},
        ];

        $scope.message = "Click on the hyper link to view the item list.";
    });
    說明:
    (1)var mainApp = angular.module("mainApp", ['ngRoute']);
    加入ngRoute模組為應用程式

    (2)$routeProvider :用來規化路由,其中when()方法是由path和route當做參數,path為#符號的路徑;route裡面有兩個參數分別為templateUrl用來指定網頁檔案以及controller控制器來指定控制器

    syntx:   when(path, route)

    (3)mainApp.controller: 控制器功能實做


    home.html
    <body ng-controller="ItemController">
        <div class="container">
            <h2> Welcome </h2>
            <p>{{message}}</p>
            <a href="#/viewItems"> View Items List</a>
        </div>   
    </body>

    viewItems.html
    <div class="container">
        <h2> View Items </h2>
        Search:
        <br/>
            <input type="text" ng-model="name" />
        <br/>
        <ul>
            <li ng-repeat="item in items | filter:name">{{item.name}} , {{item.city}}</li>
        </ul>
    </div>

留言