Ajax trong AngularJS

AngularJS cung cấp điều khiển $http mà làm như là service để đọc dữ liệu từ server. Server có thể tạo các lời gọi tới cơ sở dữ liệu để nhận các bản ghi. AngularJS cần dữ liệu dưới định dạng JSON. Khi dữ liệu sẵn sàng, $http có thể được sử dụng để nhận dữ liệu từ server theo cách sau đây:

function sinhvienController($scope,$http) {
var url="dulieuSV.txt";
   $http.get(url).success( function(response) {
                           $scope.sinhvienk60 = response; 
                        });
}

Ở đây tệp dulieuSV.txt chứa các bản ghi về sinh viên. $http service tạo một ajax call và lấy kết quả trả về cho đối tượng sinh viên. "sinhvien" model có thể dùng để vẽ bảng với HTML.

Các ví dụ:

dulieuSV.txt

[
{
"HovaTen" : "Tran Minh Chinh",
"MSSV" : 20150456,
"Diemthi" : "8.0"
},
{
"HovaTen" : "Nguyen Thi Chinh",
"MSSV" : 20150457,
"Diemthi" : "9.0"
},
{
"HovaTen" : "Ha Kieu Linh",
"MSSV" : 20150458,
"Diemthi" : "8.5"
},
{
"HovaTen" : "Ho Ngoc Ha",
"MSSV" : 20150459,
"Diemthi" : "9.5"
}
]

viduAJAX.html

<html>
<head>
<title>Vi du AJAX trong AngularJS</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>Ung dung AngularJS</h2>
<div ng-app="" ng-controller="sinhvienController">
<table>
   <tr>
      <th>Ho va Ten</th>
      <th>MSSV</th>
	  <th>Diem thi</th>
   </tr>
   <tr ng-repeat="sinhvien in sinhvienk60">
      <td>{{ sinhvien.HovaTen }}</td>
      <td>{{ sinhvien.MSSV }}</td>
	  <td>{{ sinhvien.Diemthi }}</td>
   </tr>
</table>
</div>
<script>
function sinhvienController($scope,$http) {
var url="dulieuSV.txt";
   $http.get(url).success( function(response) {
                           $scope.sinhvienk60 = response;
                        });
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

Kết quả:

Để chạy ví dụ này, bạn cần tạo viduAJAX.html and dulieuSV.txt tới một webserver. Mở tệp viduAJAX.html với địa chỉ URL trên server trên một trình duyệt web và xem kết quả.

Mở tệp viduAJAX.html để xem kết quả

Theo tutorialspoint

Bài trước: Cú pháp Include trong AngularJS

Bài tiếp: Thành phần View trong AngularJS

Thứ Năm, 26/07/2018 15:01
31 👨 434
0 Bình luận
Sắp xếp theo
    ❖ AngularJS