Open In App

AngularJS For Loop with Numbers & Ranges

Last Updated : 10 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

AngularJS is used to develop dynamic single-page web applications and is also useful for building the most attractive UI for the application. In some scenarios, we need to print the elements in the application in a loop manner, so for this scenario, we can use the For Loop to iterate over the numbers and also use the Ranges. In web development looping over the data or the numbers is mainly done to perform the actions or most probably to generate the content dynamically. So in AngularJS, we can do this using the For Loop with Numbers & Ranges. In this article, we will see the approaches to how we can use For Loop with Numbers and ranges.

Steps to configure the AngularJS Application

The below steps will be followed for configuring the AngularJS Application:

  • Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.
mkdir loop-range
cd loop-range
  • Create the index.html file in the newly created folder, we will have all our logic and styling code in this file. We can also create separate files for HTML, CSS, and JS.

We will understand the above concept with the help of suitable approaches & will understand its implementation through the illustration.

Using ng-repeat (For Loop with Numbers)

In this approach, we are using the ng-repeat directive in AngularJS to create the For Loop with Numbers. In this approach we have taken two custom buttons, in which one button will generate 1-10 numbers using a loop and another button will generate even numbers using a loop. There is a ‘$timeout’ function used that manages the intervals of output generation. Mainly, the ng-repeat which is used in this example is used to iterate over the arrays of generated numbers and then display them dynamically on the web page.

Example: Below is an example that demonstrates the use of For Loop with Numbers using ng-repeat in AngularJS.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>
          AngularJS For Loop with Numbers
      </title>
    <script src=
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }
  
        h1 {
            color: green;
        }
  
        h3 {
            color: blue;
        }
  
        .results-container {
            display: flex;
            justify-content: space-around;
        }
  
        .results-box {
            background-color: #f0f0f0;
            padding: 10px;
            border: 1px solid #ccc;
            margin: 10px;
            width: 35%;
        }
  
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
        }
    </style>
</head>
  
<body ng-controller="myController">
    <h1>GeeksforGeeks</h1>
    <h3>
          Approach 1: Using ng-repeat
        (For Loop with Numbers)
      </h3>
    <button ng-click="genNum()">
          Click to Generate 1-10 Numbers
      </button>
    <button ng-click="genEvenNum()">
          Click Generate Even 1-10 Numbers
      </button>
    <div class="results-container">
        <div class="results-box" ng-show="num">
            <h4>Generated 1-10 Numbers:</h4>
            <ul>
                <li ng-repeat="result in loopResults.numbers">
                      {{ result }}
                  </li>
            </ul>
        </div>
        <div class="results-box" ng-show="evenNum">
            <h4>
                  Generated Even 1-10 Numbers:
              </h4>
            <ul>
                <li ng-repeat="result in loopResults.evenNumbers">
                      {{ result }}
                  </li>
            </ul>
        </div>
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myController", function ($scope, $timeout) {
            $scope.loopResults = {
                numbers: [],
                evenNumbers: []
            };
            $scope.num = false;
            $scope.evenNum = false;
            $scope.genNum = function () {
                $scope.loopResults.numbers = [];
                $scope.num = true;
                for (var i = 1; i <= 10; i++) {
                    (function (number) {
                        $timeout(function () {
                            $scope.loopResults.numbers.push(
                              "Generated number: " + number);
                            console.log("Generated number:", number);
                        }, 1000 * number);
                    })(i);
                }
            };
            $scope.genEvenNum = function () {
                $scope.loopResults.evenNumbers = [];
                $scope.evenNum = true;
                for (var i = 2; i <= 10; i += 2) {
                    (function (number) {
                        $timeout(function () {
                            $scope.loopResults.evenNumbers.push(
                              "Generated even number: " + number);
                            console.log("Generated even number:", number);
                        }, 1000 * (number / 2));
                    })(i);
                }
            };
        });
    </script>
</body>
  
</html>


Output:

For

Using a Custom ng-repeat with Range

In this approach, we were using the custom ng-repeat directive with the Range of numbers. Here, the user is allowed to dynamically enter the input as start and end values and after clicking on the button, the dynamic generation and output display of a list of numbers is done within the range specified by the user. This approach is more suitable for making flexible applications as this approach mainly reduces the necessity of hardcoding the numerical range in the code.

Example: Below is an example that demonstrates the use of Ranges using custom ng-repeat in AngularJS.
 

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>
          AngularJS Range Example
      </title>
    <script src=
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }
  
        h1 {
            color: green;
        }
  
        h3 {
            color: blue;
        }
  
        .range-container {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            margin-top: 20px;
        }
  
        .range-input {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 10px;
        }
  
        .range-input label {
            margin-right: 10px;
        }
  
        .range-result {
            list-style-type: none;
            padding: 0;
            display: flex;
        }
  
        .range-result li {
            background-color: #f0f0f0;
            padding: 10px;
            border: 1px solid #ccc;
            margin-right: 10px;
        }
  
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
        }
    </style>
</head>
  
<body ng-controller="myController">
    <h1>GeeksforGeeks</h1>
    <h3>
          Approach 2: Using a Custom
        ng-repeat with Range
      </h3>
    <div class="range-container">
        <div class="range-input">
            <label for="start">    
                  Start:    
              </label>
            <input type="number"
                   ng-model="start"
                   id="start">
        </div>
        <div class="range-input">
            <label for="end">
                  End:
              </label>
            <input type="number" 
                   ng-model="end" 
                   id="end">
        </div>
        <button ng-click="generateRange()">
              Generate Range
          </button>
        <ul class="range-result">
            <li ng-repeat="number in range">
                  {{ number }}
              </li>
        </ul>
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myController", function ($scope) {
            $scope.range = [];
            $scope.start = 1;
            $scope.end = 10;
            $scope.generateRange = function () {
                $scope.range = [];
                var start = parseInt($scope.start);
                var end = parseInt($scope.end);
                if (!isNaN(start) && !isNaN(end) && start <= end) {
                    for (var i = start; i <= end; i++) {
                        $scope.range.push(i);
                    }
                    console.log("Generated range:", $scope.range);
                } else {
                    console.log("Invalid input. Please "+
                                "enter valid start and end values.");
                }
            };
        });
    </script>
</body>
  
</html>


Output:

Range



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads