我有一个 PhoneGap + Onsen UI + AngularJS 应用程序正在开发中,我在 View 中有一个列表,其中的项目将从 Controller 变量中获取。
我希望能够通过单击从列表中删除项目。
列表如下所示:
<ons-list>
<ons-list-item modifier="tappable" class="item" ng-repeat="citem in completeditems" ng-click="delete(citem)">
<ons-row>
<ons-col>
<div class="titlediv">
<header>
<span class="item-title">{{citem.name}}</span>
</header>
</div>
<div class="item-dates">
<span class="item-start">{{citem.start}}</span>
</div>
</ons-col>
</ons-row>
</ons-list-item>
</ons-list>
$scope 中的 completeditems 对象如下所示:
var completeditemname = "item" + i;
$scope.completeditems[completeditemname] = {
id : "ID",
name : "Name for it",
start: "Start date"
}
试了下面的方法,还是不行:
$scope.delete = function(item) {
var index = $scope.completeditems.indexOf(item);
$scope.completeditems.splice(index,1);
//$scope.completeditems.remove(item); //tried this aswell
$scope.$apply() //i need this to update the view
}
最佳答案
您不需要 $scope.$apply()
调用。当您对范围变量进行更改时,无论如何都会触发摘要循环,我相信您会因此遇到错误。
UPDATED:: 从外观上看,您正在处理一个实际对象,因此我更新了 plunker 中的代码以帮助您解决问题。这意味着改变 ng-repeat
以同时使用键和值。
这是一个简单的 plunkr,显示了您在删除函数 http://plnkr.co/edit/NtQD... 中试图用一个衬里做什么的基本示例。 .
<body ng-app="myApp">
<div ng-controller="myController as ctrl">
<ul ng-repeat="(key, value) in ctrl.items track by key">
<li ng-click="ctrl.delete(key)">{{value}}</li>
</ul>
</div>
</body>
var myApp = angular.module('myApp', [])
.controller('myController', [
'$scope',
function($scope) {
var self = this;
self.items = {
item1: {
id: 1,
name: 'a'
},
item2: {
id: 2,
name: 'b'
},
item3: {
id: 3,
name: 'c'
}
};
self.delete = function(key) {
delete self.items[key];
};
}
]);
希望对您有所帮助!
关于javascript - 从 ng-repeat 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32377464/