How to use ng-repeat with AngularJS

In this tutorial I will speak about the ng-repeat directive. Ng-repeat works in the same way as foreach function from PHP. Ng-repeat provides an easy way to sort an array of objects.

A sample example:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app>
<div ng-controller="Items">
<div ng-repeat="item in items">
{{item}}
</div>
</div>
<script language="javascript">
function Items($scope)
{
$scope.items = ['one','two','three','four','five'];
}
</script>
</body>
</html>

Output:

one
two
three
four
five
Another example:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app>
<div ng-controller="Items">
<div ng-repeat="(number,value) in items">
{{number}} = {{value}}
</div>
</div>
<script language="javascript">
function Items($scope)
{
$scope.items = {'one':1,'three':3,'two':2};
}
</script>
</body>
</html>
Output:
one = 1
three = 3
two = 2








Leave a Comment