AngularJS - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

AngularJS Tables

AngularJS Tables

shape Description

Tables are considered as one of the key elements of website designing and mainly used for displaying the data, especially the repeated data. AngularJS Tables are designed by ng-repeat directive. The directive works on a single page HTML DOM element. It can loop over a group of items and generates HTML from it i.e. it repeats only the DOM element to which it is added. Remember that, table data is normally repeatable by nature. In this chapter, how to create the AngularJS tables using ng-repeat directive is explained.

shape Examples

index.html [html] <h1>AngularJS Tables</h1> <div ng-app="spApp"> <div ng-controller="SPController"> <table cellspacing="0" cellpadding="0" class="table"> <colgroup span="7"></colgroup> <tbody> <tr class="days"> <th title="Monday">Monday</th> <th title="Tuesday">Tuesday</th> <th title="Wednesday">Wednesday</th> <th title="Thursday">Thursday</th> <th title="Friday">Friday</th> <th title="Saturday">Saturday</th> <th title="Sunday">Sunday</th> </tr> <tr ng-repeat="days in dates"> <td ng-repeat="day in days"> {{ day }} </td> </tr> </tbody> </table> </div> </div> [/html] Controller.js [javascript] var myApp = this.angular.module('spApp', []); var monthDays = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]; myApp.controller('SPController', function($scope) { var dates = []; for (var i = 0; i < monthDays.length; i++ ) { if (i % 7 == 0) dates.push([]); dates[dates.length-1].push(monthDays[i]); } return $scope.dates = dates; }); [/javascript] style.css [css] td,th { border:1px solid #ccc; text-align:center; } [/css] From the above example, AngularJS creates one <tr> element for each item in the dates array and creates one <td> element for each item in the days array. Output:

Summary

shape Key Points

  • AngularJS Tables use ng-repeat directive.
  • Only the DOM element to which it is added is repeated.