This tutorial will guide you through the process of using ng-repeat to iterate over keys and values of a JavaScript object.
In AngularJS, the ng-repeat directive is commonly used to iterate over arrays and objects. When iterating over objects, you might want to access both keys and values.
Prerequisites
- Basic understanding of AngularJS directives.
- Familiarity with JavaScript object structure.
Syntax
The syntax for iterating over keys and values with ng-repeat in AngularJS is as follows:
<element ng-repeat="(key, value) in JSObject">
Contents...
</element>
It indicates that you can use ng-repeat on an element to iterate over the keys and values of the specified JavaScript object (JSObject), where key and value are the variables that will hold the key-value pairs during each iteration.
Example 1: Iterating Over Simple Object
Let’s start with a simple example where we have a JavaScript object containing various properties. We’ll use ng-repeat to iterate over the keys and values of this object and display them.
HTML Structure
This section describes the basic structure of the HTML document where the AngularJS application is defined and initialized.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<!-- ng-repeat directive will be applied here -->
<div ng-repeat="(key, value) in sam">
<!-- Display key and value -->
<p>{{key}} - {{value}}</p>
</div>
<script type="text/javascript">
// AngularJS code will be defined here
</script>
</body>
</html>
Explanation:
- This is a basic HTML structure with AngularJS included. The
ng-appdirective is used to define the AngularJS application module. - The
ng-controllerdirective is applied to the<body>element, specifying that the controller namedMyControllerwill manage this part of the HTML.
AngularJS Code
This section contains the AngularJS code responsible for defining the application module and controller, as well as initializing the data to be displayed.
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', function($scope) {
// Controller logic goes here
$scope.sam = {
Name: "CodersPacket",
Location: "Murshidabad",
Type: "Edu-Tech",
};
}]);
Explanation:
- A new AngularJS module named
myAppis created using theangular.modulefunction. This module will contain the controller and other components of the AngularJS application. - The
myApp.controllerfunction defines a new controller namedMyControllerwithin themyAppmodule. - The controller function takes
$scopeas a dependency, which is used to communicate between the controller and the view. - Inside the controller function, the
$scope.samvariable is defined as an object with three properties:Name,Location, andType.
ng-repeat Directive
This section explains how the ng-repeat directive is used to iterate over the key-value pairs of the sam object and display them in the HTML view.
<div ng-repeat="(key, value) in sam">
<p>{{key}} - {{value}}</p>
</div>
Explanation:
- The
ng-repeatdirective is applied to the<div>element, which will repeat its contents for each key-value pair in thesamobject defined in the controller. (key, value)is a special syntax used byng-repeatto iterate over object properties. For each iteration,keywill contain the current property key, andvaluewill contain the corresponding value.- Inside the
ng-repeatblock, a<p>element is used to display the key-value pair using AngularJS expressions ({{key}}and{{value}}).
Overall, this code demonstrates how to use the ng-repeat directive in AngularJS to iterate over the properties of an object and display them in the HTML view.
Example 2: Iterating Over Nested Object
Now, let’s consider a scenario where we have a nested JavaScript object. We’ll use ng-repeat to iterate over the keys and values of this nested object and display them.
HTML Structure
This section outlines the basic structure of the HTML document where the AngularJS application is defined and initialized.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<!-- ng-repeat directive will be applied here -->
<div ng-repeat="(key, value) in materials">
<!-- Nested ng-repeat directive -->
<h1>{{key}}</h1>
<div ng-repeat="(key1, value1) in value">
<!-- Display nested key-value pairs -->
<p>{{key1}} - {{value1}}</p>
</div>
</div>
<script type="text/javascript">
// AngularJS code will be defined here
</script>
</body>
</html>
Explanation:
- This is a basic HTML structure with AngularJS included. The
ng-appdirective is used to define the AngularJS application module. - The
ng-controllerdirective is applied to the<body>element, specifying that the controller namedMyControllerwill manage this part of the HTML.
AngularJS Code
This section contains the AngularJS code responsible for defining the application module and controller, as well as initializing the data to be displayed.
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', function($scope) {
// Controller logic goes here
$scope.materials = {
diamond: {
hardness: "Ultra Hard",
goodFor: "Display, cutting"
},
gold: {
hardness: "Hard",
goodFor: "Jewelry"
},
silver: {
hardness: "comparatively soft",
goodFor: "Jewelry, Display"
}
};
}]);
Explanation:
- A new AngularJS module named
myAppis created using theangular.modulefunction. This module will contain the controller and other components of the AngularJS application. - The
myApp.controllerfunction defines a new controller namedMyControllerwithin themyAppmodule. - The controller function takes
$scopeas a dependency, which is used to communicate between the controller and the view. - Inside the controller function, the
$scope.materialsvariable is defined as an object with three properties (diamond,gold, andsilver), each containing nested key-value pairs.
ng-repeat Directives
This section explains how the ng-repeat directive is used to iterate over the key-value pairs of the materials object and display them in the HTML view.
<div ng-repeat="(key, value) in materials">
<!-- Nested ng-repeat directive -->
<h1>{{key}}</h1>
<div ng-repeat="(key1, value1) in value">
<!-- Display nested key-value pairs -->
<p>{{key1}} - {{value1}}</p>
</div>
</div>
Explanation:
- The outer
ng-repeatdirective is applied to a<div>element, instructing AngularJS to repeat the element for each key-value pair in thematerialsobject. (key, value)is a special syntax used byng-repeatto iterate over object properties. For each iteration,keywill contain the current property key, andvaluewill contain the corresponding value.- Inside the outer
ng-repeatblock, there is a nestedng-repeatdirective applied to a<div>element. This nested directive repeats the element for each key-value pair in thevalueobject (which is nested within thematerialsobject). - The
<h1>element displays the outer key (diamond,gold, orsilver), and the nested<div>displays the nested key-value pairs within a<p>element.
Overall, this code demonstrates how to use nested ng-repeat directives in AngularJS to iterate over a hierarchical structure of key-value pairs and display them in the HTML view.
Additional Tips
Here are some additional tips related to iterating over keys and values using ng-repeat in AngularJS.
Displaying in a Table Format
If you want to display the keys and values in a table format, you can use the following code snippet:
<table>
<tr ng-repeat="(key, value) in data">
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
</table>
Explanation:
- This code snippet illustrates how to present key-value pairs in a table format using the
ng-repeatdirective. - Each row of the table corresponds to a key-value pair, with
{{key}}and{{value}}used to display the respective values.
Editing Property Values with Two-Way Binding
To enable two-way binding for editing property values, you can use the following code snippet:
<tr ng-repeat="(key, value) in data">
<td>{{key}}<input type="text" ng-model="data[key]"></td>
</tr>
Explanation:
- This snippet showcases how to enable two-way data binding for editing property values directly in the view.
- The
ng-modeldirective binds the input field to the corresponding property in thedataobject, allowing changes to be reflected bidirectionally.
Customizing Display Order:
To avoid the display of key-values in alphabetical order, you can follow the procedure below:
JavaScript
// JavaScript
$scope.data = {
"id": 2,
"project": "wewe2012",
"date": "2013-02-26",
"description": "ewew",
"eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
var test = {};
test[key]=$scope.data[key];
array.push(test);
}
$scope.data = array;
HTML
<!-- HTML -->
<p ng-repeat="obj in data">
<font ng-repeat="(key, value) in obj">
{{key}} : {{value}}
</font>
</p>
Explanation:
- The JavaScript code restructures the original object into an array, ensuring a specific order of key-value pairs.
- The HTML code then uses nested
ng-repeatto iterate over the modified object, displaying keys and values in the desired order.