Skip to content
Related Articles

Related Articles

Improve Article

How to make empty an array using AngularJS ?

  • Last Updated : 14 Oct, 2020

The task is to make empty an array or delete all elements from the array in AngularJS.

Approach: First example uses the [] notation to reinitialize the array which eventually removes all the elements from the array. Second example sets the length of the array to 0 by using length property, which also empty the array.

Example 1:




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
    </script>
  
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.arr = ['Geek', 'GeeksForGeeks', 'gfg'];
            $scope.emptyArr = function () {
                $scope.arr = [];
  
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        How to empty an array in AngularJS
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            Array = {{arr}}<br><br>
            <button ng-click='emptyArr()'>
                Clear Array
            </button>
        </div>
    </div>
</body>
  
</html>

Output:



Example 2:




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
    </script>
      
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.arr = ['Geek', 'GeeksForGeeks', 'gfg'];
            $scope.emptyArr = function () {
                $scope.arr.length = 0;
  
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        How to empty an array in AngularJS
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            Array = {{arr}}<br><br>
            <button ng-click='emptyArr()'>
                Clear Array
            </button>
        </div>
    </div>
</body>
  
</html>

Output:

Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :