AngularJS 视图Views
AngularJS支持单页面应用程序通过一个页面上的多个视图。 要做到这一点,AngularJS提供了ng-view ng-template指令,$routeProvider服务。
ng-view指令
ng-view指令简单地创建一个占位符,相应的视图(HTML或ng-template视图)可以基于配置。
使用
定义一个div内ng-view主模块。
<div ng-app = "mainApp"> ... <div ng-view></div> </div>
ng-template指令
ng-template指令是用来创建一个HTML视图使用脚本标记。 它包含id属性是使用$routeProvider地图视图与控制器。
使用
定义一个脚本块型内ng-template主要模块。
<div ng-app = "mainApp"> ... <script type = "text/ng-template" id = "addStudent.htm"> <h2> Add Student </h2> {{message}} </script> </div>
$routeProvider服务
$routeProvider是一个关键的服务集的配置url,地图与相应的HTML页面或ng-template和高度相同的控制器。
使用1
定义一个脚本块型内ng-template主要模块。
<div ng-app = "mainApp"> ... <script type = "text/ng-template" id = "addStudent.htm"> <h2> Add Student </h2> {{message}} </script> </div>
使用2
定义一组脚本块主模块和路由配置。
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模块使用关键“$routeProvider”。
$routeProvider。 当定义一个URL " / addStudent”映射到“addStudent.htm”。 addStudent。 htm应该出现在相同的路径为主要的HTML页面。 如果HTML页面没有定义,那么需要使用ng-template id =“addStudent.htm”。 我们使用ng-template。
“否则”用于设置默认视图。
“控制器”是用于设置相应的控制器的视图。
例子
下面的例子显示了使用所有上述指令。
testAngularJS.htm
<html> <head> <title>Angular JS Views</title> <script src = "https://www.yangzhiw.cn/static/js/angularjs-1.5.8/angular.min.js"></script> <script src = "https://www.yangzhiw.cn/static/js/angularjs-1.5.8/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>
输出
打开文件testAngularJS.htm在web浏览器并查看结果。
当我们点击Add Student或者View Students的时候,下面的内容会发生变化,输出相对于的内容。