Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete item from data-bound JSON list using AngularJs

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!

like image 993
Dan Avatar asked Sep 13 '13 11:09

Dan


2 Answers

splice works fine here:

<a ng-click="deleteItem($index)">x</a>

$scope.deleteItem = function (index) {
    Messages.data.splice(index, 1);
}

http://jsfiddle.net/L82S7/1/

like image 182
noj Avatar answered Sep 30 '22 12:09

noj


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.

like image 25
Chandermani Avatar answered Sep 30 '22 11:09

Chandermani