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

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

问题描述

简单的待办事项列表,但每个项目的列表页面上都有一个删除按钮:

p>

相关模板HTML:

 < tr ng-repeat =person在人中> 
< td> {{person.name}} - #{{person.id}}< / td>
< td> {{person.description}}< / td>
< td nowrap = nowrap>
< a href =#!/ edit>< i class =icon-edit>< / i>< / a>

相关控制器方法:

  $ scope.delete = function(person){
API.DeletePerson({id:person.id},function(success){
//我需要一些代码从我的范围拉人。
});
};

我试过 $ scope.persons.pull(person) $ scope.persons.remove(person)



虽然数据库删除成功,但我可以不从范围中拉出这个项目,我不想为客户端已有的数据调用服务器的方法,我只想从范围中移除这个人。



任何想法?

解决方案

您的问题与Angular不同,但使用Array方法。从数组中删除特定项目的正确方法是使用 方法Array.splice 。此外,使用ng-repeat时,您可以访问特殊的 $ index 属性,该属性是您传入的数组的当前索引。



解决方案实际上非常简单:

查看:

 < a ng-click =delete($ index)>删除< / 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);
});
};


Simple to-do list, but with a delete button on list page for each item:

Relevant template 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>

Relevant controller method:

$scope.delete = function (person) {
  API.DeletePerson({ id: person.id }, function (success) {
    // I need some code here to pull the person from my scope.
  });
};

I tried $scope.persons.pull(person) and $scope.persons.remove(person).

Although the database 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.

Any ideas?

解决方案

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.

The solution is actually pretty straightforward:

View:

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

Controller:

$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天全站免登陆