Skip to content
Related Articles

Related Articles

Improve Article
How to update an array element in AngularJS ?
  • Last Updated : 14 Oct, 2020

The task is to update an array element with the help of AngularJS.

Approach: To update a particular item in an array, there are 2 ways either by its value or by its index. In the first example, the element is updated by its value and in the second example, it has been updated using the index by the bracket notation.

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.array = ['Geeks', 'Geek', 'gfg', 'GFG'];
            $scope.updateEl = function (item) {
                var index = $scope.array.indexOf(item);
                if (index > -1) {
                    $scope.array[index] = 'GeeksForGeeks';
                }
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        How to update an array 
        element in AngularJS
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            <p>Update element in array = {{array}}</p>
            <input type="button" 
                value="change element 'gfg' " 
                ng-click="updateEl('gfg')">
        </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.array = ['Geeks', 'Geek', 'gfg', 'GFG'];
            $scope.updateEl = function (index) {
                if (index > -1) {
                    $scope.array[index] = 'GeeksForGeeks';
                }
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        How to update an array 
        element in AngularJS
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            <p>Update element in array = {{array}}</p>
            <input type="button" 
                value="change element at index 3 " 
                ng-click="updateEl(3)">
        </div>
    </div>
</body>
  
</html>      

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :