5

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!

0

2 Answers 2

19

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I must have implemented splice wrongly. This works perfectly, thanks!
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.