How to push elements in an array using AngularJS ?
Given an array and the task is to perform the push operation on array using AngularJS.
Approach: In this approach, the push() method is used to insert the element at the end of the array. In the first example, a static value ‘Geek’ is inserted in the array and in the second example a input box is provided to the user to push the value they want.
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 = ['GFG', 'GeeksForGeeks']; $scope.val = "Geek"; $scope.push = function () { $scope.arr.push($scope.val); }; }); </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p > How to push element in array in AngularJS </ p > < div ng-app = "app" > < div ng-controller = "controller" > value to push - "{{val}}"< br > Array = {{arr}}< br >< br > < button ng-click = 'push()' > Click to push </ 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 = ['GFG', 'GeeksForGeeks']; $scope.push = function () { // get the input value var inputVal = $scope.arrInput; $scope.arr.push(inputVal); }; }); </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p > How to push element in array in AngularJS </ p > < div ng-app = "app" > < div ng-controller = "controller" > Input here: < input type = "text" name = "arrExample" ng-model = "arrInput" > < br >< br > Array = {{arr}}< br >< br > < button ng-click = 'push()' > Click to push </ button > </ div > </ div > </ body > </ html > |
Output: