How to delete an item or object from the array using ng-click ?
Last Updated :
10 Jun, 2020
Improve
The task is to delete the item from the list when the button is clicked. This all should be done by using ng-click. This is done by using the splice() method. The syntax for the method is given below.
Syntax for splice() function:
javascript
Output:
javascript
Output:
Before Click:
After click:
array.splice(indexno, noofitems(n), item-1, item-2, ..., item-n)Example for splice() function:
const topics = ['Array', 'String', 'Vector'];
let removed=topics.splice(1, 1);
['Array', 'Vector']The keywords in syntax are explained here:
- indexno: This is required quantity. Definition is integer that specifies at what position to add/remove items. If it is negative means to specify the position from the end of the array.
- noofitems(n): This is optional quantity. This indicates a number of items to be removed. If it is set to 0, no items will be removed.
- item-1, ...item-n:This is also optional quantity. This indicates new item(s) to be added to the array
<!DOCTYPE html>
<html>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<script>
var app = angular.module("studentNames", []);
</script>
<div ng-app="studentNames"
ng-init="names= ['Madhavi', 'Shivay', 'Priya']">
<ul>
<li ng-repeat="x in names track by $index">{{x}}
<span ng-click="names.splice($index, 1)">
<strong>x</strong</span>
</li>
</ul>
<input ng-model="addItem">
<button ng-click="names.push(addItem)">Add</button>
</div>
<p>Click the small x given in front of
name to remove an item from the name list.</p>
</body>
</html>

