Open In App

How to count array items in AngularJS ?

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array and the task is to get the length of an array variable in AngularJS. For this, we will be using the .length() method to get the length of an array variable.

Syntax:

array.length();

Example 1: In this example, the array length is shown by the alert box. Here, we have an array containing different array elements & we need to find the total count of the elements in an array. We have created the Controller that will calculate the total length of an array element & will display the count while clicking the button.

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
    </script>
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function($scope) {
            $scope.arr = ['GFG', 'Geek', 'Geeks', 'GeeksforGeeks'];
            $scope.length = '';
            $scope.getLen = function() {
                $scope.length = $scope.arr.length;
                alert("Array Length = " + $scope.length);
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <p> How to count array items in AngularJS </p>
    <div ng-app="app">
        <div ng-controller="controller">
            <p>Array = {{arr}}</p>
            <button ng-click="getLen()">
                Click To Get Length 
            </button>
        </div>
    </div>
</body>
</html>


Output:

 

Example 2: In this example, length is shown inside the <p>element. Here, we have created a controller that is responsible to render the array with the elements, along with having a button that will display the total length of an array while clicking the button. Inside the controller, we have an array & using the arr.length() method, we will count the length of an array.

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
    </script>
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function($scope) {
            $scope.arr = ['GFG', 'Geek', 'Geeks', 'GeeksforGeeks'];
            $scope.length = '';
            $scope.getLen = function() {
                $scope.length = $scope.arr.length;
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <p
        How to count array items in AngularJS 
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            <p>Array = {{arr}}</p>
            <button ng-click="getLen()"
                Click To Get Length
            </button>
            <p>Length is = {{length}}</p>
        </div>
    </div>
</body>
</html>


Output:

 



Last Updated : 21 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads