我正在尝试编写一个函数,使我能够在单击按钮时删除一个项目,但我认为我对该函数感到困惑 - 我是否使用 $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();
};
最佳答案
要删除项目,您需要将其从数组中删除,并且可以将 bday
项目传递给标记中的删除函数。然后在 Controller 中查找项目的索引并从数组中删除
<a class="btn" ng-click="remove(item)">Delete</a>
然后在 Controller 中:
$scope.remove = function(item) {
var index = $scope.bdays.indexOf(item);
$scope.bdays.splice(index, 1);
}
Angular 会自动检测到 bdays
数组的变化并做 ng-repeat
演示:http://plnkr.co/edit/ZdShIA?p=preview
编辑:如果使用服务器进行实时更新将使用您使用 $resource
创建的服务来管理阵列更新,同时它会更新服务器
关于html - 如何使用 ng-click 从数组中删除项目或对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15453979/