How to make empty an array using AngularJS ?
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 > |
chevron_right
filter_none
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 > |
chevron_right
filter_none
Output: