扫码一下
查看教程更方便
AngularJS Ajax是通过提供 $http 控件来实现的,它可以从服务器读取数据。AngularJS 需要 JSON 格式的数据。数据准备好后,可以使用 $http 通过以下方式从服务器获取数据
function studentController($scope,$https:) {
var url = "/demo_source/angularjs/data.txt";
$https:.get(url).success( function(response) {
$scope.students = response;
});
}
这里,文件 data.txt 包含学生记录。$http 服务进行 ajax 调用并设置对其属性 students 的响应。students 模型可用于在 HTML 中绘制表格。
data.txt
[ { "Name" : "Mahesh Parashar", "RollNo" : 101, "Percentage" : "80%" }, { "Name" : "Dinkar Kad", "RollNo" : 201, "Percentage" : "70%" }, { "Name" : "Robert", "RollNo" : 191, "Percentage" : "75%" }, { "Name" : "Julian Joe", "RollNo" : 111, "Percentage" : "77%" } ]
从服务器获取数据代码如下
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" 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>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController',function($scope,$http) {
var url = "/demo_source/angularjs/data.txt";
$http.get(url).then( function(response) {
$scope.students = response.data;
});
});
</script>