Learning AngularJS Part 2/4

Simple List using ngRepeat

Posted on 2015-08-18 04:01:00 in webdev, angular

Using ngRepeat - A List of Angular Projects

Although this is only the second one I’ve learned about, I think ngRepeat will be my favorite directive. It reminded me of some of the features I have used in backbone. ngRepeat helps a developer remember to avoid code repetition — a key principle of programming. Instead of hard coding data into HTML, ngRepeat lets you use a template so that you don’t have to repeat yourself.

Here is all you need for a table with N rows:

<table id="table" class="table table-hover table-mc-light-blue">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Description</th>
      <th>Link</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="project in projects"> 
      <td data-title="ID">{{project.id}}</td>
      <td data-title="Name">
        <a href="{{project.link}}" target="_blank">{{project.name}}</a>
      </td>
      <td data-title="Description">{{project.description}}</td>
      <td data-title="Link">
        <a href="{{project.inAction}}" target="_blank">Link</a>
      </td>
      <td data-title="Status">{{project.status}}</td>
    </tr>
  </tbody>
</table>

ngRepeat loops through the projects and asks for each one’s attributes. Every time it finds a new “project” in “projects” it creates a new replica of the html skeleton and populates it.

Of course the data needs to come from somewhere. The data is held in an object (which could be stored and automatically updated by a server. Here is the data structure that I used:

angular.module("myapp", [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
})
.controller("index", ["$scope", function($scope) {
    $scope.projects = [
    {id: 1, name: "Using the ngClass Directive", description: "A Prime Number Detector",
	link: "", inAction: "", status: "Completed"},
    {id: 2, name: "Using the ngRepeat Directive", description: "You're looking at it",
	link: "", inAction: "", status: "In Progress"},
    {id: 3, name: "Using the ngShow Directive", description: "A Riddle Verifier",
	link: "", inAction: "", status: "Completed"},
    {id: 4, name: "Using $watch to Update the View", description: "A Palindrome Maker",
	link: "", inAction: "", status: "Completed"}
    ];
}]);

As I upload more projects, I will add all the info here and I won’t have to touch the HTML. Just this feature alone can simplify the development of many applications. Sites that deliver dynamic content–like news sites–take advantage of this to make their job much easier.

See it on Github