Bye*_*Bye 153 html javascript angularjs
简单的待办事项列表,但每个项目的列表页面上都有一个删除按钮:
相关模板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>
相关控制器方法:
$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(person)和$scope.persons.remove(person).
虽然数据库已成功删除,但我无法从作用域中提取此项目,并且我不想对客户端已有的数据进行服务器方法调用,我只是想从范围中删除这一个人.
有任何想法吗?
Jos*_*ber 309
你必须找到的索引person你的persons数组,然后使用数组的splice方法:
$scope.persons.splice( $scope.persons.indexOf(person), 1 );
Jos*_*ler 257
您的问题不是使用Angular,而是使用Array方法.从数组中删除特定项的正确方法是Array.splice.此外,使用ng-repeat时,您可以访问特殊$index属性,该属性是您传入的数组的当前索引.
解决方案实际上非常简单:
视图:
<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);
  });
};
我会使用具有有用功能列表的Underscore.js库.
withoutRun Code Online (Sandbox Code Playgroud)without_.without(array, *values)返回数组的副本,其中删除了所有值的实例.
Run Code Online (Sandbox Code Playgroud)_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
var res = "deleteMe";
$scope.nodes = [
  {
    name: "Node-1-1"
  },
  {
    name: "Node-1-2"
  },
  {
    name: "deleteMe"
  }
];
$scope.newNodes = _.without($scope.nodes, _.findWhere($scope.nodes, {
  name: res
}));
请参阅JSFiddle中的演示.
filterRun Code Online (Sandbox Code Playgroud)var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); // => [2, 4, 6]
$scope.newNodes = _.filter($scope.nodes, function(node) {
  return !(node.name == res);
});
请参阅小提琴中的演示.
$scope.removeItem = function() {
    $scope.items.splice($scope.toRemove, 1);
    $scope.toRemove = null;
};
这对我有用!
| 归档时间: | 
 | 
| 查看次数: | 254818 次 | 
| 最近记录: |