AngularJS如何从范围中删除项目 [英] AngularJS How to remove an Item from scope

查看:111
本文介绍了AngularJS如何从范围中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简易待办事项清单,但清单页面上的删除按钮为每个项目!

1。有关HTML模板:

    <tr ng-repeat="person in persons">
        <td>{{person.name}} - # {{person.id}}</td>
        <td>{{person.description}}</td>
        <td nowrap=nowrap>
            <a href="#!/edit"><i class="icon-edit"></i></a>
            <button ng-click="delete(person)"><i class="icon-minus-sign"></i></button>
        </td>
    </tr>

2。相关负责人方法:

$scope.delete = function (person) {
    API.DeletePerson({ id: person.id }, function (success) {
    **// I NEED SOME CODE HERE TO PULL THE PERSON FROM MY SCOPE**
    });
};

我试图$ scope.persons.pull(人)

我试图$ scope.persons.remove(人)

虽然分贝删除成功,我不能拉从范围这个项目,我不想做一个方法调用到服务器进行数据的客户端已经有,我只是想删除范围此一人。

Although the db deleted successfully, I can not pull this item from scope and I do not want to make a method call to the server for data the client already has, I just want to remove this one person from scope.

任何想法?

解决方案:


  1. 去该指数是在HTML正确的做法:

  1. Going for the index was the correct approach in the HTML:

不过,只是改变了角度参数(IDX)是不够的,我不得不创建者的实例来欢送到服务器上删除。

However, just changing the angular parameter to (idx) was not enough, I had to create an instance of that person to send off to the server for deletion.

$scope.delete = function (idx) {

    var delPerson = $scope.persons[idx];

    API.DeletePerson({ id: delPerson.id }, function (success) {

        $scope.persons.splice(idx, 1);
    });
};


谢谢你们!

角是伟大的,我鼓励大家谁都有没有检查出来!
    };

Angular is GREAT and I encourage everyone who hasn't already to check it out! };

推荐答案

您的问题是不是真的有角,但阵列的方法。从阵列中移除一个特别项目正确的方法是用<一个href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice\"><$c$c>Array.splice.此外,使用NG重复的时候,你有机会获得特殊的 $指数属性,它是你传递的数组的当前索引。

Your issue is not really with Angular, but with Array methods. The proper way to remove a particularly item from an array is with Array.splice. Also, when using ng-repeat, you have access to the special $index property, which is the current index of the array you passed in.

该解决方案实际上是pretty简单:

The solution is actually pretty straightforward:

查看:

<a ng-click="delete($index)">Delete</a>

控制器:

$scope.delete = function ( idx ) {
  var person_to_delete = $scope.persons[idx];

  API.DeletePerson({ id: person_to_delete.id }, function (success) {
    $scope.persons.splice(idx, 1);
  });
};

这篇关于AngularJS如何从范围中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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