tharindu
tharindu

Reputation: 523

Populate html Table from values of an json array using ng-if

I have an array json as follows

$scope.array =[{"id":"1","age":"3","name":"ab"},{"id":"2","age":"2","name":"ee"},{"id":"3","age":"1","name":"dd"}];

I need to show these data in a table using ng-if where if the age is 1 then that cell should have only data related to age = 1 etc. I used the following code.

    <html>
    <table>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
<tr>
    <tr ng-repeat="record in array">
    <td ng-if="record.age == '1'">{{record.id}} {{record.name}}</td>
    <td ng-if="record.age == '2'">{{record.id}} {{record.name}}</td>
    <td ng-if="record.age == '3'">{{record.id}} {{record.name}}</td>
    </table>
    </html>

But currently all the values are shown in the first column one after the other. I can't figure out the reason.

Upvotes: 1

Views: 76

Answers (1)

cortereal
cortereal

Reputation: 31

Don't forget to close your tr tag with an end tag. Something like this:

<tr>
    <th>one</th>
    <th>two</th>
    <th>three</th>
</tr>

<tr>
    <tr ng-repeat="record in array">
        <td ng-if="record.age == '1'">{{record.id}} {{record.name}}</td>
        <td ng-if="record.age == '2'">{{record.id}} {{record.name}}</td>
        <td ng-if="record.age == '3'">{{record.id}} {{record.name}}</td>
    </tr>
</tr>

However, in your case, you won't gain nothing by using ng-if. You will get the same output if you use the following code:

<tr>
    <th>one</th>
    <th>two</th>
    <th>three</th>
</tr>

<tr>
    <tr ng-repeat="record in array">
        <td>{{record.id}} {{record.name}}</td>
    </tr>
</tr>

If you really want to use a ng-if, the way that you're doing is fine.

Upvotes: 1

Related Questions