Trying CRUD with $resource in a service [team]

posted in: AngularJS | 0

Using $resource for CRUD needed some extra know how.

Here is the service

angular.module('todomvc').service('todoCollection', function($resource) {
    return $resource
    ('http://localhost:3000/todos/:id',
        {
            id: '@id'
        },
        {
            update: {
                method: 'PUT'
            }
        }
    );
});

Here is the controller snippet accessing the service

            var todo = todoCollection.get({ id: 1 }, function() {
                console.log(todo);
            });

            var todos = todoCollection.query(function() {
                console.log(todos);
            });

            var newTodo = {
                "id": null,
                "title": "test",
                "completed": false
            };

            todoCollection.save(newTodo);

            var deleteTodo = {
                "id": 2
            };

            todoCollection.delete(deleteTodo);

            var updateTodo = {
                "id": 3,
                "title": "test has now been updated",
                "completed": true
            };

            todoCollection.update(updateTodo);

Leave a Reply