OdeToCode IC Logo

The Special Properties of ngRepeat In AngularJS

Thursday, April 17, 2014

Today’s tip comes straight from the AngularJS documentation, but I’ve seen a few people miss the topic. 

Inside an ngRepeat directive the special properties $first, $last, and $middle are available. These properties hold boolean values ($first is true only for the first repeated element), and two more special properties that are available are $even and $odd.

Another useful property is the $index property, which contains the offset of each repeated element and starts at 0 (like all good offsets).

You can view the following markup live in this Plunker. The code is using $first and $last to avoid showing clickable up and down prompts when an item is in the first or last position. The markup is also using $index to grab the offset of a clicked item.

<table>
    <tr ng-repeat="item in items">
        <td>{{item.title}}</td>
        <td><span ng-show="!$first" ng-click="moveUp($index)">up</span></td>
        <td><span ng-show="!$last" ng-click="moveDown($index)">down</span></td>
    </tr>
</table>

Combined with the following controller, you can move items up and down by clicking on the arrows.

module.controller("mainController", function($scope){
    $scope.items = [
        { title: "Item 1" },
        { title: "Item 2" },
        { title: "Item 3" },
        { title: "Item 4" },
        { title: "Item 5" },
    ];

    var move = function (origin, destination) {
        var temp = $scope.items[destination];
        $scope.items[destination] = $scope.items[origin];
        $scope.items[origin] = temp;
    };

    $scope.moveUp = function(index){            
        move(index, index - 1);
    };

    $scope.moveDown = function(index){                    
        move(index, index + 1);
    };

});