什么是AngularJS中的模板
AngularJS中的模板是简单的HTML文件,其中填充或丰富了AngularJS的东西,如属性和指令。一个指令是一个标记元素,用来锁定一个特定的属性或类,以根据需要呈现其行为。Angular中的模型和控制器与模板相结合,以操纵用户在其浏览器中看到的视图。Angular模板还可以容纳CSS、表单控件、过滤器和表达式。有两种类型的模板。
- Static Template
- Dynamic Templates
以下是说明这两种模板的例子。
静态模板:静态模板是通过使用一个脚本标签来定义的。必须提供一个id和type属性,其值为text/ng-template,才能使静态模板发挥作用。另外,需要注意的是,静态模板只有在ng-app范围内才能工作,否则,Angular会忽略它。一个静态模板可以通过使用ng-include指令来呈现。
For example:
<div ng-include="'geeksforgeeks.html'"></div>
实例1:本实例演示了AngularJS中的简单静态模板。
<!DOCTYPE html>
<html ng-app>
<head>
<script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<title>Angular Static Template</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
h1 {
color: green;
}
</style>
</head>
<body ng-controller="GeekController">
<h1>GeeksforGeeks</h1>
<h3>Angular Static Template</h3>
<br> Input Value is:
<input ng-model="geek" value="Your Value Here">
<button ng-click="gfg()">Button</button>
<script src="angular.js"></script>
</body>
</html>
输出:

动态模板:正如其名称所示,动态模板用于与运行时环境一起工作。它是由Angular根据用户的需求进行编译和渲染的。一个动态模板可以通过使用ng-include指令来渲染。
For example:
<div ng-include="'templates/geeksforgeeks.html'"></div>
例子2:这个例子演示了AngularJS中的动态模板。
<html>
<head>
<title>Angular Dynamic Template</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>
<style>
body {
text-align: center;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
color: green;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h3>Angular Dynamic Template</h3>
<div ng-app="gfg">
<p>
<a href="#addCourse">Add Course</a>
</p>
<p>
<a href="#viewCourses">View Courses</a>
</p>
<div ng-view></div>
<script type="text/ng-template"
id="addCourse.htm">
<h2> Add Course </h2> {{message}}
</script>
<script type="text/ng-template"
id="viewCourses.htm">
<h2> View Courses </h2> {{message}}
</script>
</div>
<script>
var gfg = angular.module("gfg", ['ngRoute']);
gfg.config(['routeProvider', function(routeProvider) {
routeProvider.when('/addCourse', {
templateUrl: 'addCourse.htm',
controller: 'AddCourseController'
}).when('/viewCourses', {
templateUrl: 'viewCourses.htm',
controller: 'ViewCoursesController'
}).otherwise({
redirectTo: '/addCourse'
});
}]);
gfg.controller('AddCourseController', function(scope) {
scope.message =
"This page will be used to display add Course";
});
gfg.controller('ViewCoursesController', function(scope) {
$scope.message =
"This page will be used to display all the Courses";
});
</script>
</body>
</html>
输出:

极客教程