in Javascript

Angular ng-repeat on object and arrays

 

ng-repeat is similar to a for loop in javascript which lets you loop through an array of objects or values and print the information in html.

For example: Suppose we have an array of people,

$scope.people = ["Max","Gene","Rose"];

To print these values in a <p> tag would have a syntax something like the one shown below.

<p ng-repeat="p in people">
{{p}}
</p>

What if we had an array of objects,

$scope.people = [{
           "name" : "Max",
           "gender" : "Male"
       },{
            "name" : "Gene",
            "gender" : "Male"
       },{
            "name" : "Rose",
            "gender" : "Female"
       }];

Our ng-repeat would look something like this

<p ng-repeat="p in people">
{{p.name}} is a {{p.gender}}
</p>

While it was easy to loop through an array of values and objects using an ng-repeat, running a loop in an object is a little different.

Suppose we have an object person

$scope.person = {
   "name" : "Max",
   "gender" : "Male",
    "age" : "28"
}

We can print the object values using an ng-repeat like this

<p ng-repeat="(key,value) in people">
{{key}} : {{value}}
</p>

The above code would produce an output which would look something like this:

name : Max
gender : Male
age : 28

Write a Comment

Comment