如何使用ng-click从数组中删除项目或对象?

266

我正在尝试编写一个函数,使我能够在按钮被点击时删除一个项目,但我认为我对该函数感到困惑了 - 我是否要使用$digest

HTML和 app.js:

<ul ng-repeat="bday in bdays">
  <li>
    <span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
    <form ng-show="editing" ng-submit="editing = false">
      <label>Name:</label>
      <input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
      <label>Date:</label>
      <input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
      <br/>
      <button class="btn" type="submit">Save</button>
      <a class="btn" ng-click="remove()">Delete</a>
    </form>
  </li>
</ul>

$scope.remove = function(){
  $scope.newBirthday = $scope.$digest();
};

2
你不需要使用 $digest,因为它用于进入 Angular 的 digest 循环(而且由于 ng-click,你已经在一个 digest 循环中了)。你是想从数组中删除一个项目吗? - Mark Rajcok
@MarkRajcok :) 是的,这就是我正在尝试做的。 - Jess McKenzie
ng-click 中的 remove() 没有上下文。需要更多的标记来显示正在被删除的内容,以及它是否在 ng-repeat 中,或者被删除的项目来自哪里,或者您想要从 remove() 中获得什么行为。 - charlietfl
@charlietfl 在ng-repeat中,我已经更新了问题。 - Jess McKenzie
12个回答

0

一种简单的内联方式就是在删除按钮中添加bdays.splice($index, 1)

  <ul ng-repeat="bday in bdays">
  <li>
    <span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
    <form ng-show="editing" ng-submit="editing = false">
      <label>Name:</label>
      <input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
      <label>Date:</label>
      <input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
      <br/>
      <button class="btn" type="submit">Save</button>
      <a class="btn" ng-click="bdays.splice($index, 1)">Delete</a>
    </form>
  </li>
</ul>

0
Pass the id that you want to remove from the array to the given function 

从控制器中(函数可以在同一个控制器中,但最好放在服务中)

    function removeInfo(id) {
    let item = bdays.filter(function(item) {
      return bdays.id=== id;
    })[0];
    let index = bdays.indexOf(item);
    data.device.splice(indexOfTabDetails, 1);
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接