簡體   English   中英

如何從 AngularJS 范圍內的數組中刪除項目?

[英]How to remove an item from an array in AngularJS scope?

簡單的待辦事項列表,但在每個項目的列表頁面上都有一個刪除按鈕:

在此處輸入圖片說明

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

雖然數據庫刪除成功,但我無法從范圍中提取此項,並且我不想為客戶端已有的數據對服務器進行方法調用,我只想從范圍中刪除此人。

有任何想法嗎?

你必須找到索引person在你的persons數組,然后使用數組的splice方法:

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

您的問題實際上並不在於 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庫。

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.removeItem = function() {
    $scope.items.splice($scope.toRemove, 1);
    $scope.toRemove = null;
};

這對我有用!

如果你有任何關聯到 list 的功能,當你做拼接功能時,關聯也會被刪除。 我的解決方案:

$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指示項目是否將被刪除。

另一個參考: 另一個例子

希望能幫到你。 問候。

對於@Joseph Silber 的公認答案不起作用,因為 indexOf 返回 -1。 這可能是因為 Angular 添加了一個哈希鍵,這對於我的 $scope.items[0] 和我的項目是不同的。 我試圖用 angular.toJson() 函數解決這個問題,但它沒有用:(

啊,我找到了原因......我使用塊方法通過觀察我的 $scope.items 在我的表中創建兩列。 對不起!

你也可以用這個

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

Angular 有一個名為arrayRemove的內置函數,在您的情況下,該方法可以簡單地為:

arrayRemove($scope.persons, person)
array.splice(array.pop(item));

要從作用域中刪除元素,請使用:

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

這里輸入鏈接描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM