<div ng-app = "mainApp"> ... <div ng-view></div> </div>
<div ng-app = "mainApp"> ... <script type = "text/ng-template" id = "addStudent.htm"> <h2> Add Student </h2> {{message}} </script> </div>
<div ng-app = "mainApp"> ... <script type = "text/ng-template" id = "addStudent.htm"> <h2> Add Student </h2> {{message}} </script> </div>
var mainApp = angular.module("mainApp", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/addStudent', { templateUrl: 'addStudent.htm', controller: 'AddStudentController' }) .when('/viewStudents', { templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController' }) .otherwise ({ redirectTo: '/addStudent' }); }]);
$routeProvider 被定义为 mainApp 模块配置下的一个函数,使用 key 作为 '$routeProvider'。
$routeProvider.when 定义了一个 URL"/addStudent",它被映射到"addStudent.htm"。 addStudent.htm 应该存在于与主 HTML 页面相同的路径中。如果未定义 HTML 页面,则需要使用 ng-template 和 id="addStudent.htm"。我们使用了 ng-template。
"otherwise"用于设置默认视图。
"controller" 用于为视图设置相应的控制器。
<html> <head> <title>Angular JS Views</title> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"> </script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp"> <p><a href = "#addStudent">Add Student</a></p> <p><a href = "#viewStudents">View Students</a></p> <div ng-view></div> <script type = "text/ng-template" id = "addStudent.htm"> <h2> Add Student </h2> {{message}} </script> <script type = "text/ng-template" id = "viewStudents.htm"> <h2> View Students </h2> {{message}} </script> </div> <script> var mainApp = angular.module("mainApp", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/addStudent', { templateUrl: 'addStudent.htm', controller: 'AddStudentController' }) .when('/viewStudents', { templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController' }) .otherwise({ redirectTo: '/addStudent' }); }]); mainApp.controller('AddStudentController', function($scope) { $scope.message = "this page will be used to display add student form"; }); mainApp.controller('ViewStudentsController', function($scope) { $scope.message = "this page will be used to display all the students"; }); </script> </body> </html>