AngularJs Remove Item From Array


AngularJs Remove Item From Array : You can use array splice method to remove an item from AngularJs array. Here in this tutorial we are going to explain how to remove an item from AngularJs Array. You can also use our online tool to run and edit the code.


AngularJs Remove Item From Array

To Remove an item from AngularJs we first need to find the item index then use splice method to remove the item by the index. Here is an example of removing an item from an array.

JavaScript Part –

JavaScript Part Contains the following script –

AngularJs Delete Item or Object From Array:

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

Html Part-

Html Part Contains the following html –

AngularJs Delete Item or Object From Array Example:

<div ng-app="myApp">  
<div ng-controller="myController">  
<p>Remove b from array = {{myArray}}</p>
<input type="button" value="Remove b " ng-click="deleteElement('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>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {
$scope.myArray = ['a','b','c','d','e'];
$scope.deleteElement = function(item) {
	 var index = $scope.myArray.indexOf(item);
	 if(index > -1){
     $scope.myArray.splice(index, 1); // will remove item 
     }	 
};
});
</script>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController">  
<p>Remove b from array = {{myArray}}</p>
<input type="button" value="Remove b " ng-click="deleteElement('b')"> 
</div> 

</body>  
</html>      

Try it »

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

AngularJs Remove Item From Array Example

If you click on the “remove b” button it will remove b from the above array.


Advertisements

Add Comment

📖 Read More