Search code examples
angularjsangular-resource

Can angular resource do a bulk restful operation?


Say I have a todo application and clicking a checkbox on any individual Todo marks it as complete and does a PUT operation.

Then there is a checkbox to 'mark all complete' or 'mark all incomplete'. This should mark every todo as completed/incomplete, regardless of what its individual status is.

When using angular-resource, what is the best practice way to update all the items. Is it possible to do it in a single bulk request and have all the items updated? Or would I be better off just updating each one individually?


Solution

  • You could extend your Angular resource by providing a custom action, for example:

    var Todo = $resource('api/todo/:todo_id', {todo_id: '@id'}, {
      markAllComplete: { method: 'POST', params: { complete: true }, isArray: true }
    }
    

    and then in your controller doing:

    // Assuming your todos have been fetched and are stored
    // in the $scope.todos variable...
    Todo.markAllComplete($scope.todos);
    

    The only thing (and arguably the hardest thing) left to do would be to code your backend to accept a POST to 'api/todo' and mark all the referenced todos as completed.