I am a new to AngularJS area and I am trying to use it with ASP.NET Web API. I am struggling right now with the Delete Function. The user should be able to delete an item from a list of items and when he deletes an item successfully, the list should be updated (or refreshed) immediately after that deletion. I already implemented the deletion function, however, the list doesn't get updated after the deletion and I don't know why.
Here's the code of deletion function in Web API:
// DELETE api/<controller>/5
public void Delete(int id)
{
itemRepository.DeleteItem(id);
}
And here's the AngularJS Controller Code:
app.controller('itemsController', ['itemsFactory', 'itemFactory', function (itemsFactory, itemFactory) {
var vm = this;
vm.message = "Welcome to Items Page";
vm.Items= itemsFactory.query();
// callback for ng-click 'deleteItem':
vm.deleteItem = function (aId) {
itemFactory.delete({ id: aId });
vm.Items= itemsFactory.query();
};
}]);
And here's the AngularJS Service Code:
app.factory('itemsFactory', function ($resource) {
return $resource('/api/items', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
});
app.factory('itemFactory', function ($resource) {
return $resource('/api/items/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: { id: '@id' } },
delete: { method: 'DELETE', params: { id: '@id' } }
})
});
So how can I get the list of items updated immediately after any successful deletion operation?
That's because itemFactory.delete in your case is $resource object which run asynchronously. So the problem is in this rows:
So to accomplish that all you need is update your vm.Items inside
itemFactory.delete
callback like this: