当属性为 0 或更低时从数组中删除对象 - 角度

Remove object from array when attribute 0 or below - Angular

本文关键字:数组 删除 对象 角度 属性      更新时间:2023-09-26

我有一个控制器,允许用户编辑对象。其中一部分递减了对象的一个属性——我的模型的数量。当模型的数量达到 0 或更低时,理想情况下我想删除整个对象。

.HTML

<div ng-app='basket'>
  <div ng-controller='BasketController as basket'>
    <div class='product' ng-repeat='product in cart.products'>{{ product.name }} Count: {{ product.quantity }} <a ng-click='product.quantity = product.quantity - 1'>Remove</a></div>
  </div>
</div>

.JS

(function(){
  var app = angular.module('basket', []);
  var cart;
  app.controller('BasketController', function($scope, $http){
    $scope.getTimes=function(n){
      return new Array(n);
    };
    $scope.cart = {};
    $scope.cart.products = [{
      'name':'item 1',
      'quantity':3
    },{
      'name':'item 2',
      'quantity':3
    },{
      'name':'item 3',
      'quantity':3
    }];
  });
})();

现场演示

http://codepen.io/EightArmsHQ/pen/bNBmXm

因此,例如,在上面,如果您在第一个对象上一次又一次地单击"删除",当您到达 0 时,我只想有一个如下所示的数组:

    $scope.cart.products = [{
      'name':'item 2',
      'quantity':3
    },{
      'name':'item 3',
      'quantity':3
    }];

您可以编写一个 remove 方法来检查数量并从列表中删除该项目。

在您的控制器中:-

$scope.remove = function(product){
  var products = $scope.cart.products;
  product.quantity -= 1;
  if(!product.quantity){
    /*Splice the object from the array based on the index*/
    products.splice(products.indexOf(product), 1);
  }
}

然后单击只需将其称为:

<a ng-click='remove(product)'>Remove</a>

演示

将链接更改为:

<a ng-click='remove(product)'>Remove</a>

并将以下方法添加到控制器:

$scope.remove = remove;
function remove(product) {
    $scope.cart.products.splice($scope.cart.products.indexOf(product), 1);
}