如何使用 ng-click 从数组中删除项目或对象? [英] How do I delete an item or object from an array using ng-click?

查看:23
本文介绍了如何使用 ng-click 从数组中删除项目或对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a function that enables me to remove an item when the button is clicked but I think I am getting confused with the function - do I use $digest?

HTML &app.js:

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

推荐答案

要删除项目,您需要将其从数组中删除,并且可以在标记中将 bday 项目传递给您的删除函数.然后在控制器中查找项目的索引并从数组中删除

To remove item you need to remove it from array and can pass bday item to your remove function in markup. Then in controller look up the index of item and remove from array

<a class="btn" ng-click="remove(item)">Delete</a>

然后在控制器中:

$scope.remove = function(item) { 
  var index = $scope.bdays.indexOf(item);
  $scope.bdays.splice(index, 1);     
}

Angular 会自动检测bdays 数组的变化,并更新ng-repeat

Angular will automatically detect the change to the bdays array and do the update of ng-repeat

演示:http://plnkr.co/edit/ZdShIA?p=preview

如果使用服务器进行实时更新将使用您使用 $resource 创建的服务来管理阵列更新,同时它更新服务器

If doing live updates with server would use a service you create using $resource to manage the array updates at same time it updates server

这篇关于如何使用 ng-click 从数组中删除项目或对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆