如何刷新删除使用AngularJS一个项目后,项目的列表? [英] How to refresh the list of items after deleting one item using AngularJS?

查看:118
本文介绍了如何刷新删除使用AngularJS一个项目后,项目的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来AngularJS区,我想用的ASP.NET Web API使用它。我现在很努力用清除功能。用户应该能够在该删除后立即从项目列表中删除一个项目时,他成功地删除项,列表应该更新(或刷新)。我已经实现了删除功能,但是,列表不会被删除后更新的,我不知道为什么。

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.

下面是在网页API删除功能的code:

Here's the code of deletion function in Web API:

// DELETE api/<controller>/5
        public void Delete(int id)
        {
            itemRepository.DeleteItem(id);
        }

和这里的AngularJS控制器code:

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();
        };
}]);

和这里的AngularJS服务code:

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' } }
    })
});

所以,我怎么能得到任何成功的删除操作后立即更新项目列表?

推荐答案

这是因为itemFactory.delete你的情况是异步运行$资源对象。所以,问题是这一行:

That's because itemFactory.delete in your case is $resource object which run asynchronously. So the problem is in this rows:

// callback for ng-click 'deleteItem':
vm.deleteItem = function (aId) {

    // You send request to the server
    itemFactory.delete({ id: aId });

    // You don't get response from the server yet, so your item hasn't deleted.
    vm.Items= itemsFactory.query();
};

因此​​,要完成所有你需要的是更新内部 itemFactory.delete 您vm.Items回调是这样的:

So to accomplish that all you need is update your vm.Items inside itemFactory.delete callback like this:

vm.deleteItem = function (aId) {
    itemFactory.delete({ id: aId }, function () {
        // Update your items after you get success response from the server after deleting
        vm.Items= itemsFactory.query();
    });
};

这篇关于如何刷新删除使用AngularJS一个项目后,项目的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆