← all articles

Create an ng-repeat iterable from an integer in AngularJS

Tamas Piros | 30 July 2015 | AngularJS | Tip of the day

One of the key features of AngularJS is ng-repeat which is a "directive that instantiates a template once per item from a collection." The key in this sentence that it can create a template for items in a collection - collections being arrays or objects. But how can you iterate through a simple integer value?

One of the most common examples that you'll see is a list that automatically generats list items:

<ul>
  <li ng-repeat="number in [1, 2, 3, 4]"> {{ number }} </li>
</ul>

Which will generate:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

Note that if you have an array that contains the same elements, i.e. [1, 1, 1] you need to use the track by $index expression - the reason being is that it's not possible to maintain a one-to-one mapping between elements in the array and DOM elements - so the following should fix the issue: ng-repeat="number in [1, 1, 1] track by $index"

Now, this is all great and works as expected but what if you have to work with a REST API that returns an integer value. Let's say that you're working on a website that displays information about hotels. The API returns to you the integer value '3' if it's a three star hotel. How can you render three ★ symbols using ng-repeat?

The answer is simple, you need to create a "helper" function inside your controller:

function HotelController($scope) {
    $http.get('/hotel/route').success(function(data)) {
        //let's assume data.stars returns an integer
        $scope.stars = getStars(data.stars);
    });
    $scope.getStars(stars) {
        return new Array(stars);
    }
}
<!-- if you're using bootstrap you could do this: -->
<span ng-repeat="$scope.star in vm.stars track by $index" class="glyphicon glyphicon-star"></span>

This would render the intended ★★★ output.

Free email mini-course on
Full Stack development

Sign up now to receive a free email mini-course covering the MEAN stack and more. Also be the first to know when we release new courses and videos.