How to create a foreach loop in Angular JS

Home > Search > How-to
  by

In this example, the Angular controller will pass each item in a variable to the View.

 

Controller

The following Controller will store the members of the Simpsons family in a variable named myVariable

var myApp = angular
	.module("myModule", [])
	.controller("myController", function ($scope) {
	var FamilyMembers = [
		{firstname: "Bart", lastname: "Simpson"},
		{firstname: "Lisa", lastname: "Simpson"},
		{firstname: "Home", lastname: "Simpson"},
		{firstname: "Marge", lastname: "Simpson"}		
		];
	
	$scope.myVariable = FamilyMembers;
});

 

View

In the view, the following markup can be used to get myMessage, which is Hello World. The ng-repeat directive is used to loop through the values in myVariable

<head>
    <script src="js/angular.min.js"></script>
    <script src="js/myAngular.js"></script>
</head>
<body ng-app="myModule">
    <div ng-controller="myController">
	<div ng-repeat="Family in myVariable">
	{{ Family.firstname }}
	{{ Family.lastname }}			
	</div>
    </div>

 


In this example, the Angular controller will pass each item in a variable to the View. There will be two loops, the classification loop and then a nested members loop.

 

Controller

The following Controller will create two classifications, Parents and Children, and then the members of each classification will be listed. 

var myApp = angular
	.module("myModule", [])
	.controller("myController", function ($scope) {
	var FamilyMembers = [
		{
			classification: "Parents",
			members: [
			{name: "Homer Simpson"},
			{name: "Marge Simpson"},		
			]
		},
		{
			classification: "Children",
			members: [
			{name: "Bart Simpson"},
			{name: "Lisa Simpson"},		
			]
		},		
	];
	
	$scope.myVariable = FamilyMembers;
});

 

View

In the view, the following markup can be used to get myMessage, which is Hello World. The ng-repeat directive is used to loop through the values in myVariable

<head>
    <script src="js/angular.min.js"></script>
    <script src="js/myAngular.js"></script>
</head>
<body ng-app="myModule">
    <div ng-controller="myController">
	<ul>
	  <li ng-repeat="Family in myVariable">
	  {{ Family.classification }}
	  <ul ng-repeat="FamilyMembers in Family.members">
	    <li> {{ FamilyMembers.name }}
	  </ul>
	</ul>
    </div>

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments