官术网_书友最值得收藏!

6.3 ng-template指令的使用

在本章前面的兩個案例中,我們把每個視圖都寫在一個單獨的HTML文件中,有時候視圖內容比較少,我們可能會希望把不同的視圖集成到同一個頁面中,或者要開發一個單頁面應用(SPA),就可以使用ng-template指令來實現。下面是一個ng-template指令的使用案例:

代碼清單:ch06\ch06_03.html

        <!doctype html>
        <html ng-app="routeModule">
        <head>
            <meta charset="UTF-8">
            <title>ch06_03</title>
            <script src="/angular-1.5.5/angular.js"></script>
            <script src="/angular-1.5.5/angular-route.js"></script>
        </head>
        <body>
            <div>
                <a href="#/view1">view1</a> <a href="#/view2">view2</a>
            </div>
            <div ng-view></div>
            <script type="text/ng-template" id="/view1.html">
                <h1>View1內容<h1>
            </script>
            <script type="text/ng-template" id="/view2.html">
                <h1>View2內容<h1>
            </script>
            <script>
                var routeModule = angular.module('routeModule', ['ngRoute'])
                routeModule.config(['$routeProvider',
                    function($routeProvider){
                        $routeProvider.
                          when('/view1', {
                            templateUrl: '/view1.html'
                          }).
                          when('/view2', {
                            templateUrl: '/view2.html'
                          })
                  }]);
            </script>
        </body>
        </html>

在上面的案例中,我們通過<script>標簽和ng-template指令定義了兩個視圖模板,id屬性分別為/view1.html和/view2.html。

        <script type="text/ng-template" id="/view1.html">
            <h1>View1內容<h1>
        </script>
        <script type="text/ng-template" id="/view2.html">
            <h1>View2內容<h1>
        </script>

路由的定義和前面介紹的相同,templateUrl為<script>標簽的id屬性。

        routeModule.config(['$routeProvider',
            function($routeProvider){

            $routeProvider.
                    when('/view1', {

            templateUrl: '/view1.html'
                    }).
                    when('/view2', {

            templateUrl: '/view2.html'
                    })
          }]);

在瀏覽器中預覽ch06_03.html,效果如圖6.5所示。

圖6.5 ng-template指令使用案例

單擊view1、view2鏈接,視口中顯示對應<script>標簽中定義的視圖內容。從中可以看出使用ng-template同樣能夠達到多視圖切換效果。

主站蜘蛛池模板: 杭锦后旗| 靖安县| 民勤县| 虎林市| 堆龙德庆县| 蓬溪县| 汽车| 阳西县| 搜索| 永和县| 盐山县| 白山市| 石首市| 遵义市| 堆龙德庆县| 高碑店市| 奉贤区| 全椒县| 阜南县| 惠州市| 监利县| 舟山市| 武乡县| 沁源县| 红河县| 开封县| 大港区| 洞口县| 莲花县| 晋城| 临湘市| 静海县| 泗水县| 灌南县| 太谷县| 柯坪县| 大庆市| 东安县| 江孜县| 西峡县| 中阳县|