Repeating multiple elements in AngularJS

Before reading this article, I highly recommended reading my previous article on angularJS.

Problem

In my previous article output is like following.

serial-no-output

But what if I want output like following.

ng repeat strart

We cannot use ng-repeat because ng-repeat has limitations that it can only work with single element.

Solution

We can do it by two ways. Firstly we can use table inside the td and do what we want to do and second is using ng-repeat-start and ng-repeat-end. I personally recommend to use the second method because its clean and we don’t write more code.

I am using my previous project so I am not going to do all these stuff like adding controller, view, js and bootstrap file in our project.

I am making some changes in index.cshtml

Method 1

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_layout.cshtml";
}
<script src="~/Scripts/Data/Data.js"></script>
<div class="table-responsive" ng-app="myModule" ng-controller="myController">
    <table class="table" style="width:600px">
        <tbody>
            <tr ng-repeat="data in dataList">
                <td>
                    <table>
                        <tr><th>SN</th><td>{{$index+1}}</td></tr>
                        <tr><th>Name</th><td ng-bind="data.Name"></td></tr>
                        <tr><th>Email</th><td ng-bind="data.Email"></td></tr>
                        <tr><th>Phone</th><td ng-bind="data.Phone"></td></tr>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>
</div>

Output

ng repeat

Output is not same as the above. We do some css manipulations for it. As of now I am not giving attention on css part. If we want same output as above we need designer. I am just focused on the output. So I am good enough to display the records.

Method 2

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_layout.cshtml";
}
<script src="~/Scripts/Data/Data.js"></script>
<div class="table-responsive" ng-app="myModule" ng-controller="myController">
    <table class="table" style="width:600px">
        <tbody>
            <tr ng-repeat-start="data in dataList">
                <th>SN</th><td>{{$index+1}}</td>
            </tr>
            <tr>
                <th>Name</th><td ng-bind="data.Name"></td>
            </tr>
            <tr>
                <th>Email</th><td ng-bind="data.Email"></td>
            </tr>
            <tr ng-repeat-end>
                <th>Phone</th><td ng-bind="data.Phone"></td>
            </tr>
        </tbody>
    </table>
</div>

Output

ng repeat strart

This is the same output which we need nothing write extra element in our html file. Code is clean.

Hope this article is helpful.

Tags: , , ,