8

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?

Christian Schlensker
  • 21,708
  • 19
  • 73
  • 121
  • That kind of depends on the API, doesn't it? You can send them all using one $http request, if the API supports such bulk loads. Otherwise you can loop over the items and do .update() on each. – holographic-principle Jun 18 '13 at 22:05
  • That sounds like a different type of object/service. I'd create a different service called TodoBulkService & extend the factory to deal with bulk actions. – Foo L Jun 18 '13 at 23:04
  • The api can handle it, or can be made to handle it. Assuming that api is "ideal" what needs to be done on the angular side, what does angular need to send to the API and what does it expect to get back? I know angular resource can have custom actions that work on the array level, is that a possible solution? – Christian Schlensker Jun 19 '13 at 05:05

1 Answers1

4

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.

alexpls
  • 1,914
  • 20
  • 29