Update array item in AngularJs


Update array item in AngularJs : It is very simple to update an item of array in AngularJs. Here in this tutorial we are going to explain how to update an item in AngularJs Array. You can also use our online tool to run and edit the code.


How to update array item in AngularJs?

To update an array item in AngularJs we first need to find the item index then assign new value using the index. Here is an example of updating an item in array.

JavaScript Part –

JavaScript Part Contains the following script –

Update array item in AngularJs: JavaScript

 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
$scope.myArray = ['a','b','c','d','e'];
$scope.updateElement = function(item) {
	 var index = $scope.myArray.indexOf(item);
	 if(index > -1){
          $scope.myArray[index] = '100'; // will update item 
         }	 
};
});
</script>

Html Part-

Html Part Contains the following html –

AngularJs update Object or Array item Example:

<div ng-app="myApp">  
<div ng-controller="myController">  
<p>Update b in array = {{myArray}}</p>
<input type="button" value="Update b " ng-click="updateElement('b')"> 
</div> 

Complete Example-

Now let us combine both javascript and html parts. Here is the complete example –

AngularJs Delete Item or Object From Array:

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
$scope.myArray = ['a','b','c','d','e'];
$scope.updateElement = function(item) {
	 var index = $scope.myArray.indexOf(item);
	 if(index > -1){
          $scope.myArray[index] = '100'; // will update item 
         }	 
};
});
</script>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController">  
<p>Update b in array = {{myArray}}</p>
<input type="button" value="Update b " ng-click="updateElement('b')"> 
</div> 

</body>  
</html>

Try it »

If you run the above example it will produce output something like this –

If you click on the “Update b” button it will update b by value 100.
Update array item in AngularJs


Advertisements

Add Comment

📖 Read More