【问题标题】:How to remove an item from an array in AngularJS scope?如何从 AngularJS 范围内的数组中删除项目?
【发布时间】:2012-12-24 09:51:22
【问题描述】:

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

相关模板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)

虽然数据库已成功删除,但我无法从范围中拉出此项目,并且我不想对服务器进行方法调用以获取客户端已经拥有的数据,我只想将这个人从范围中删除。

有什么想法吗?

【问题讨论】:

  • 我运行这个 whit $route,但视图无法正常工作。删除后我总是得到一个空白页面:-(
  • 这不是从范围中删除,而是从数组中删除,无论角度如何,它都是一样的,它只是 javascript

标签: javascript html angularjs


【解决方案1】:

您必须在persons 数组中找到person 的索引,然后使用数组的splice 方法:

$scope.persons.splice( $scope.persons.indexOf(person), 1 );

【讨论】:

  • 这是一个更好的答案;当列表已被过滤以使视图中的索引与范围内的数组中的索引不同时有效。
  • 这确实是更好的答案。请注意,除了 Andrew 提到的过滤列表用例之外,这种方法还涵盖了删除多个人员并且这些删除的 Ajax 请求返回乱序的情况。如果您在 Ajax 调用返回之前使用了行索引,您最终会删除错误的行。
  • 在某些情况下更好,但使用 indexOf 你必须遍历所有项目以找到正确的项目,在 Josh 答案中,你可以更快地获得索引和项目
  • @mike - 使用this polyfill
【解决方案2】:

您的问题不在于 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);
  });
};

【讨论】:

  • @ScottMalachowski 你是对的。我忘记了那部分。我修改了我的答案以反映这一点,所以它与你的一致。
  • 小心 - 如果您在视图中使用同一对象的多个 ng-repeat(例如,计划任务、未计划任务、已完成任务都来自 $scope.tasks,则此基于索引的解决方案将不起作用) 因为您将拥有多个索引为 2、3、4 等的项目。
  • 上面的评论,@shacker,关于同一数组的不同过滤集的多个 ng-repeat 是正确的。使用下面的方法与 indexOf
  • @AndrewKuklewicz - indexOf 可能是一项更昂贵的操作;没有过滤,这是完全没有必要的。但是通过过滤,indexOf 将是合适的方法。
  • 我正在为此苦苦挣扎,不得不对上面的标签生成进行微小的更改 - 使用 {{ }} 删除({{$index}}) 否则我得到了字符串 $index - 但我有问题,因为它从不调用该方法。当我删除像 delete() 这样的索引时,它确实如此,但这并没有真正的帮助。
【解决方案3】:

我会使用 Underscore.js 库,它有一个有用的函数列表。

without

without_.without(array, *values)

返回删除所有值实例的数组副本。

_.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 中查看演示。


filter

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

Fiddle 中查看演示。

【讨论】:

  • 我可能会使用$scope.nodes = _.without($scope.nodes, node);,因为他引用了node
  • 在现代浏览器上,您可以使用Array.prototype.filter_.filter(array, fun) 变为 array.filter(fun)
【解决方案4】:

Angular 有一个名为 arrayRemove 的内置函数,在您的情况下,该方法可以简单地是:

arrayRemove($scope.persons, person)

【讨论】:

    【解决方案5】:
    $scope.removeItem = function() {
        $scope.items.splice($scope.toRemove, 1);
        $scope.toRemove = null;
    };
    

    这对我有用!

    【讨论】:

      【解决方案6】:

      如果你有任何关联到列表的函数,当你创建拼接函数时,关联也会被删除。我的解决方案:

      $scope.remove = function() {
          var oldList = $scope.items;
          $scope.items = [];
      
          angular.forEach(oldList, function(x) {
              if (! x.done) $scope.items.push( { [ DATA OF EACH ITEM USING oldList(x) ] });
          });
      };
      

      列表参数名为items。 参数 x.done 指示该项目是否将被删除。

      其他参考:Another example

      希望对您有所帮助。问候。

      【讨论】:

        【解决方案7】:

        对于@Joseph Silber 的公认答案不起作用,因为 indexOf 返回 -1。这可能是因为 Angular 添加了一个哈希键,这对于我的 $scope.items[0] 和我的项目是不同的。我试图用 angular.toJson() 函数解决这个问题,但它不起作用:(

        啊,我找到了原因...我使用块方法通过查看我的 $scope.items 在表中创建两列。对不起!

        【讨论】:

          【解决方案8】:

          你也可以用这个

          $scope.persons = $filter('filter')($scope.persons , { id: ('!' + person.id) });
          

          【讨论】:

            【解决方案9】:
            array.splice(array.pop(item));
            

            【讨论】:

              【解决方案10】:

              要从作用域中删除元素,请使用:

              // remove an item
                  $scope.remove = function(index) {
                      $scope.items.splice(index, 1);
                  };
              

              来自enter link description here

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2023-01-16
                • 2016-10-30
                • 2014-10-16
                • 2017-08-22
                • 2021-10-19
                相关资源
                最近更新 更多