Tạo bảng trong AngularJS

Dữ liệu bảng thường được lặp lại theo thứ tự tự nhiên. Trong AngularJS, ng-repeat directive có thể được sử dụng để vẽ các bảng một cách dễ dàng. Dưới đây là ví dụ về cách sử dụng ng-repeat để tạo ra các bảng.

<table>
   <tr>
      <th>Ho va Ten</th>
      <th>Diem thi</th>
   </tr>
   <tr ng-repeat="monhoc in sinhvien.tenMonHoc">
      <td>{{ monhoc.ten }}</td>
      <td>{{ monhoc.diemthi }}</td>
   </tr>
</table>

Để tạo style cho bảng, bạn có thể được sử dụng CSS style.

<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>

Ví dụ:

Dưới đây là ví dụ cụ thể cho directive được giới thiệu bên trên.

<html>
<head>
<title>Tao bang trong AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<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="ungdungAngularjs" ng-controller="sinhvienController">
<table border="0">
<tr><td>Nhap ho:</td><td><input type="text" ng-model="sinhvien.ho"></td></tr>
<tr><td>Nhap ten: </td><td><input type="text" ng-model="sinhvien.ten"></td></tr>
<tr><td>Ho va Ten: </td><td>{{sinhvien.hoten()}}</td></tr>
<tr><td>Mon Hoc:</td><td>
<table>
   <tr>
      <th>Ho va Ten</th>
      <th>Diem thi</th>
   </tr>
   <tr ng-repeat="monhoc in sinhvien.tenMonHoc">
      <td>{{ monhoc.ten }}</td>
      <td>{{ monhoc.diemthi }}</td>
   </tr>
</table>
</td></tr>
</table>
</div>
<script>
var ungdungAngularjs = angular.module("ungdungAngularjs", []);

ungdungAngularjs.controller('sinhvienController', function($scope) {
   $scope.sinhvien = {
      ho: "Tran Minh",
      ten: "Chinh",
      hocphi:200,
      tenMonHoc:[
         {ten:'Vat Ly Dai Cuong',diemthi:7.0},
         {ten:'Triet Hoc',diemthi:8.5},
         {ten:'Toan',diemthi:7.5},
		 {ten:'Tieng Anh',diemthi:9.5},
		 {ten:'Kinh Te',diemthi:9.0}
      ],
      hoten: function() {
         var doituongsinhvien;
         doituongsinhvien = $scope.sinhvien;
         return doituongsinhvien.ho + " " + doituongsinhvien.ten;
      }
   };
});
</script>
</body>
</html>

Theo tutorialspoint

Bài trước: Các Filter trong AngularJS

Bài tiếp: Hướng dẫn cài đặt AngularJS

Thứ Tư, 25/07/2018 13:56
31 👨 711
Xác thực tài khoản!

Theo Nghị định 147/2024/ND-CP, bạn cần xác thực tài khoản trước khi sử dụng tính năng này. Chúng tôi sẽ gửi mã xác thực qua SMS hoặc Zalo tới số điện thoại mà bạn nhập dưới đây:

Số điện thoại chưa đúng định dạng!
Số điện thoại này đã được xác thực!
Bạn có thể dùng Sđt này đăng nhập tại đây!
Lỗi gửi SMS, liên hệ Admin
0 Bình luận
Sắp xếp theo
❖
    Chia sẻ
    Chia sẻ FacebookChia sẻ Twitter
    Đóng