Delete item from data-bound JSON list using AngularJs
19,110
Solution 1
splice
works fine here:
<a ng-click="deleteItem($index)">x</a>
$scope.deleteItem = function (index) {
Messages.data.splice(index, 1);
}
Solution 2
Yes splice
works fine. I have done it in a different way see here http://jsfiddle.net/cmyworld/NEPZF/1/
Basically i pass the item itself.
Author by
Dan
Updated on June 18, 2022Comments
-
Dan almost 2 years
I have a list of messages which are bound as an HTML list from a JSON source. There is a delete button next to each image. I'd like to remove a message from the list when the delete button next to that message is clicked.
HTML:
<div ng-app="myApp"> <ul ng-controller="MessagesCtrl"> <li ng-repeat="message in messages.data" id="message{{message.id}}"> <a href="#" class="messageIcon">{{message.message}}</a> <a ng-click="deleteItem()">x</a> </li> </ul> </div>
JS:
var myApp = angular.module("myApp", []); myApp.factory("Messages", function () { var Messages = {}; Messages.data = [ { id: "1", message: "Message 1" }, { id: "2", message: "Message 2" }, { id: "3", message: "Message 3" }, { id: "4", message: "Message 4" } ]; return Messages; }); function MessagesCtrl($scope, Messages) { $scope.messages = Messages; $scope.deleteItem = function () { var id = this.message.id; //alert(id); Messages.data.delete({ id: id }, function () { $("#message" + id).fadeOut(); }); }
}
Fiddle: http://jsfiddle.net/L82S7/
The examples I've found to do this use either '.delete' or '.splice' - both of which yield console errors like this:
TypeError: Object #<Object> has no method 'splice'
Can anyone suggest how to get this working?
Thanks!