Tables in AngularJS are used to display the data. Displaying the data using tables is very easy. Let’s take a look at the example of table. In this example, we’ll use the ng-repeat directive to display data within a table.
HTML Code
- <div ng-app="MyApp" ng-controller="studentController">
- <table border="0">
- <tr>
- <td>Enter first name:</td>
- <td><input type="text" ng-model="student.firstName"></td>
- </tr>
- <tr>
- <td>Enter last name: </td>
- <td> <input type="text" ng-model="student.lastName"> </td>
- </tr>
- <tr>
- <td>Name: </td>
- <td>{{student.fullName()}}</td>
- </tr>
- <tr>
- <td>City: </td>
- <td>{{student.city}}</td>
- </tr>
- <tr>
- <td>State: </td>
- <td>{{student.state}}</td>
- </tr>
- <tr>
- <td>Subjects:</td>
- <td>
- <table>
- <tr>
- <th>Name</th>
- <th>Marks</th>
- </tr>
- <tr ng-repeat="subject in student.subjects">
- <td>{{ subject.name }}</td>
- <td>{{ subject.marks }}</td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- </div>
Script Code
- <script>
- var mainApp = angular.module("MyApp", []);
- mainApp.controller('studentController', function($scope) {
- $scope.student = {
- firstName: "Akshay",
- lastName: "Manocha",
- city: "Gurgaon",
- state: "Haryana",
- subjects: [{
- name: 'English',
- marks: 75
- }, {
- name: 'Math',
- marks: 99
- }, {
- name: 'Computer Science',
- marks: 60
- }, {
- name: 'French',
- marks: 75
- }, {
- name: 'Hindi',
- marks: 75
- }],
- fullName: function() {
- var studentObject;
- studentObject = $scope.student;
- return studentObject.firstName + " " + studentObject.lastName;
- }
- };
- });
- </script>
In the above code, we’ve created two variables (“firstName” and “secondName”) and assigned these variables along with their value to our $scope variable (“$scope.student”). Then, we’ve created an array of name “subjects”. At last, we have a simple function that will simply concatenate the first name and last name.
CSS
- <style>
- table,
- th,
- td {
- border: 1px solid grey;
- border-collapse: collapse;
- padding: 5px;
- }
-
- table tr:nth-child(odd) {
- background-color: #8fdfe8;
- }
-
- table tr:nth-child(even) {
- background-color: #ffffff;
- }
- </style>
For more information on AngularJS, please visit this
blog.