Angularjs Foreach


Angularjs Foreach(angularjs.foreach)- angularjs.foreach is used to iterate object collection items which can be an object or an array. Here in this tutorial we are going to explain how you can use foreach loop in AngularJs. You can use our online demo try and edit the code online.


Angularjs Foreach Array | Objects | Example

Syntax

Syntax for angular.foreach function is –

Angularjs Foreach Array | Objects | Syntax :

angular.forEach(obj, iterator, [context]);

Agruments

  • obj – Object or array to iterate.
  • iterator – Iterator function.
  • context(optional) – Object to become context.

Return

This will retrun Reference to object or array.

Angularjs Foreach Array Example

Let us create a simple example for Foreach Array loop –

Angularjs Foreach Array Example:

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.html= '';
 var myArray = [];
 myArray['99'] = 'John';
 myArray['100'] = 'Kelly';
 myArray['490'] = 'Ryan';
  $scope.foreachExample = function() {
  angular.forEach(myArray, function(value, key) {
  $scope.html += "Id : "+key+", Name: "+value+" | ";
  });
  }
});
</script>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController">  
    Result = {{html}}
	<br>
    <button ng-click ="foreachExample()">foreach Example</button>
	<br>
	
</div> 
</div>
</body>  
</html>

Try it »

Angularjs Foreach Object | JSON Example

Let us create a simple example for Foreach object loop –

Angularjs Foreach Object | JSON Example:


<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
 $scope.html= '';
 var myObj = { "Name" : "Rimi", "Password" : "123123"};
  $scope.foreachExample = function() {
  angular.forEach(myObj, function(value, key) {
  $scope.html += "key : "+key+", value: "+value+" | ";
  });
  }
});
</script>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController">  
    Result = {{html}}
	<br>
    <button ng-click ="foreachExample()">foreach Example</button>
	<br>
	
</div> 
</div>
</body>  
</html>

Try it »

If you run the above example it will produce the output something like this –

Angularjs Foreach Array | Objects | Example  Syntax


Advertisements

Add Comment

📖 Read More