AngularJS提供了$http控件,該控件可作為從服務(wù)器讀取數(shù)據(jù)的服務(wù)。服務(wù)器進(jìn)行數(shù)據(jù)庫(kù)調(diào)用以獲取所需的記錄。AngularJS需要JSON格式的數(shù)據(jù)。數(shù)據(jù)準(zhǔn)備好后,可以使用$http通過(guò)以下方式從服務(wù)器獲取數(shù)據(jù)-
function studentController($scope,$https:) {
var url = "data.txt";
$https:.get(url).success( function(response) {
$scope.students = response;
});
}這里,檔案data.txt包含學(xué)生記錄。$http服務(wù)發(fā)出一個(gè)ajax調(diào)用并設(shè)置對(duì)其屬性students的響應(yīng)。學(xué)生模型可以用來(lái)繪制HTML表格。
[
{
"Name" : "Sea Gull",
"RollNo" : 101,
"Percentage" : "80%"
},
{
"Name" : "Dinkar Kad",
"RollNo" : 201,
"Percentage" : "70%"
},
{
"Name" : "Robert",
"RollNo" : 191,
"Percentage" : "75%"
},
{
"Name" : "Julian Joe",
"RollNo" : 111,
"Percentage" : "77%"
}]<html>
<head>
<title>Angular JS Includes</title>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS-Ajax使用示例</h2>
<div ng-app = "" ng-controller = "studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat = "student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
<script>
function studentController($scope,$http) {
var url = "/run/angularjs/data.txt";
$http.get(url).then( function(response) {
$scope.students = response.data;
});
}
</script>
<script src = "https://cdn.staticfile.org/angular.js/1.2.15/angular.min.js">
</script>
</body>
</html>測(cè)試看看?/?輸出結(jié)果

要執(zhí)行此示例,您需要將testAngularJS.htm和data.txt文件部署到Web服務(wù)器。在網(wǎng)絡(luò)瀏覽器中使用服務(wù)器的URL打開(kāi)文件testAngularJS.htm,然后查看結(jié)果。