To remove items from collection in AngularJS, we can again use the same .splice Javascript function described in the previous post.
Almost all code of below code snippets are same as previous posts except highlighted code.
<script>
var members = [
{ username: 'SheoNarayan', address: 'Hyderabad' },
{ username: 'Munna', address: 'Bokaro' },
{ username: 'Jay', address: 'Aurangabad' },
{ username: 'Sreeni', address: 'New York' }
];
var app = angular.module("app", []);
app.controller("MemberController", ["$scope", function ($scope) {
$scope.Members = members;
// $scope.itemIndex = 2; // optional to declare
$scope.RemoveMember = function (index) {
$scope.Members.splice(index, 1);
}
}]);
</script>
<div ng-app="app">
<h4>Listing item from the collection</h4>
<div ng-controller="MemberController">
<ul>
<li ng-repeat="member in Members">
{{$index + 1}}. Name: {{member.username }} | Address: {{ member.address}}
</li>
</ul>
<p>
Index of item to remove : <input type="number" name="itemIndex" ng-model="itemIndex" />
<button ng-click="RemoveMember(itemIndex)">Remove member</button>
</p>
</div>
</div>
In the script block, we have added a RemoveMember behavior/method that is accepting index of item to remove and using .splice() function of JavaScript to remove that item. To know more about .splice() function and how it works, read this post.
In HTML code, we have created a number text box with ng-model as itemIndex
and the same is being passed to the RemoveMember(itemIndex) function that is called when the button is clicked.
Here AngularJS is intelligent enough to understand that this itemIndex is same as the ng-model specified in the text box. Alternatively, we can also declare a model property called itemIndex
in the controller (see the commented code above).
Output
Views: 21609 | Post Order: 25