Deleting an Item from a List Using ng-click and splice() in AngularJS
In this step-by-step guide, we’ll show you how to delete an item from a list when a button is clicked using AngularJS. We’ll be using the ng-click directive and the JavaScript splice() method to achieve this.
Step 1: Understanding splice() Method
The splice() method is used to remove items from an array and optionally add new ones. Here’s the basic syntax:
array.splice(index, numberOfItemsToRemove, item1, item2, ..., itemN);
index: The position where items should be added or removed.
numberOfItemsToRemove: The number of items to remove (set to 0 if no items are to be removed).
item1, item2…: Optional new items to be added to the array.
Example of splice() in Action
Let’s look at a simple example to understand how splice() works:
const topics = ['Array', 'String', 'Vector'];
let removed = topics.splice(1, 1);
console.log(topics);
//Output
['Array', 'Vector']
In this example, the item at index 1 (‘String’) is removed from the topics array.
Step 2: Using ng-click and splice() in AngularJS
Now let’s apply this concept in an AngularJS application. We’ll create an array of student names and delete an item when a button is clicked.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-app="studentApp" ng-controller="studentController">
<ul>
<li ng-repeat="student in studentNames">
{{ student }}
<button ng-click="deleteStudent($index)">Delete</button>
</li>
</ul>
</div>
<script>
var app = angular.module("studentApp", []);
app.controller("studentController", function($scope) {
$scope.studentNames = ['John', 'Sara', 'Mike', 'Anna'];
$scope.deleteStudent = function(index) {
$scope.studentNames.splice(index, 1);
};
});
</script>
</body>
</html>
How It Works:
a) We created a list of student names in the AngularJS controller.
b) The ng-repeat directive is used to loop through the studentNames array and display each name with a “Delete” button.
c) When the “Delete” button is clicked, the deleteStudent() function is triggered using the ng-click directive.
d) The deleteStudent() function removes the selected item from the array using the splice() method.