Showing posts with label ng-repeat. Show all posts
Showing posts with label ng-repeat. Show all posts

Friday, February 13, 2015

Using ng-repeat to Process JSON response from the server Ajax calls

In the previous posts we saw on how to use the ng-repeat directive to handle 1-dimentional arrays and arrays of objects.

ng-repeat directive
Using ng-repeat to process an array of objects


In this post we shall see a more real time scenario of using ng-repeat directive to process JSON data which is received from a server side API call. The following example does an API call using the $http services to get a JSON response containing a list of report details, the view iterates through the reports in the JSON and displays the report id and name in the HTML view

Ajax call
$http.get(…)
            .then(function (results) {
                //Success;
                try {
                    scope. reports = results.data;
                }
                catch (err) {
                    alert(err.message);
                }
            }, function (results) {
                //error
                alert("Error: " + results.data + "; "
                                      + results.status);
            }
)

UI to Process JSON
<ul ng-repeat="report in reports">
    <li>{{report.Name}} - {{report.Name}}</li>
</ul>

Wednesday, February 11, 2015

Using ng-repeat to process an array of objects

In the previous post ng-repeat directive we saw on how to use the ng-repeat directive to display items in a 1-dimentional array, however in real time we will have to deal with complex collections, a typical example could be to display a table/list which has multiple columns, in this case each row will have multiple properties, ng-repeat directive can handle these by parsing an array of objects.

The following example shows on how to process an array, where each element in the array is an object having its own set of properties.

<html ng-app>
<head>
    <meta charset="utf-8" />
    <title>AngularJS - Basic</title>
    <script src="angular.min.js"></script>
</head>
<body>
<div ng-init="Employees=[
{id:1,Name:'Tom'},
{id:2,Name:'Harry'},
{id:3,Name:'Peter'}]">
<ul>
   <li ng-repeat="emp in Employees">
     {{ emp.id }} - {{ emp.Name }}<br/>
   </li>
  </ul>
</div>
</body>

</html>

Output:



ng-repeat directive

The ng-repeat directive can be used to iterate through a collection and process one item at a time from the collection. This is similar to the foreach loop in C#. The ng-repeat directive comes in handy when we want to display a list of items in an array/collection in the view.

The following example shows how to use the ng-repeat directive to display a list of array items using the ng-repeat directive.