- AngularJS入門與進階
- 江榮波
- 338字
- 2020-11-28 23:44:34
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同樣能夠達到多視圖切換效果。
推薦閱讀
- The Complete Rust Programming Reference Guide
- WildFly:New Features
- C++ Builder 6.0下OpenGL編程技術
- Arduino開發實戰指南:LabVIEW卷
- Mastering LibGDX Game Development
- 人人都懂設計模式:從生活中領悟設計模式(Python實現)
- 琢石成器:Windows環境下32位匯編語言程序設計
- 深入理解Android:Wi-Fi、NFC和GPS卷
- Creating Stunning Dashboards with QlikView
- Python全棧數據工程師養成攻略(視頻講解版)
- Julia for Data Science
- C#程序設計(項目教學版)
- 計算機應用基礎項目化教程
- Appcelerator Titanium:Patterns and Best Practices
- HTML5游戲開發實戰