Can angular resource do a bulk restful operation?
Asked Answered
S

1

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?

Sarraceniaceous answered 18/6, 2013 at 21:35 Comment(3)
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.Personify
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.Tousle
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?Sarraceniaceous
M
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.

Mannuela answered 21/2, 2014 at 9:0 Comment(1)
This is not restful. It's rpc.Roop

© 2022 - 2024 — McMap. All rights reserved.