AngularJS 單頁應用視圖切換依賴:
type="text/ng-template",id 對應 templateUrl。<div ng-app="mainApp">
<a href="#addStudent">新增學生</a>
<a href="#viewStudents">查看列表</a>
<div ng-view></div> <!-- 視圖渲染於此 -->
<script type="text/ng-template" id="addStudent.html">
<h2>新增學生</h2> {{message}}
</script>
<script type="text/ng-template" id="viewStudents.html">
<h2>學生列表</h2> {{message}}
</script>
</div>
var mainApp = angular.module('mainApp', ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/addStudent', {
templateUrl: 'addStudent.html', // 對應 ng-template id
controller: 'AddStudentController'
})
.when('/viewStudents', {
templateUrl: 'viewStudents.html',
controller: 'ViewStudentsController'
})
.otherwise({ redirectTo: '/addStudent' });
}]);
mainApp.controller('AddStudentController', ['$scope', function($scope) {
$scope.message = '此頁顯示新增學生表單';
}]);
mainApp.controller('ViewStudentsController', ['$scope', function($scope) {
$scope.message = '此頁顯示所有學生資料';
}]);
templateUrl 優先匹配外部 HTML 檔,找不到才回退同名 ng-template。otherwise 設定預設導向路由。Controller 後綴,語義清晰。angular-route.min.js 獨立模組(1.2+ 版本)。見原文 testAngularJS.html,瀏覽器打開即可看到視圖切換效果。圖片展示了兩個標籤頁互相切換的截圖。