我是Angular JS的初学者,通过创建没有数据库连接的测试页来学习。我创建了一个示例应用程序,用户输入ID&全名 。在表中显示已注册的数据,然后选择特定的 复选框,用户必须从表和用户详细信息中删除。
问题:当我检查第二个(102个用户)并点击删除按钮时,103个用户被删除。我是角度JS的新手,
HTML:
<div class="controls" ng-controller="myUSerSignupCtrl">
<input class="controlsspace" ng-model="userid" ng-required="true" placeholder="Please Enter UserId" id="txtUserID" type="text" />
<input class="controlsspace" ng-required="true" placeholder="Please Enter FullName" ng-model="fullname" id="txtFullName" type="text" />
<button style="height: 25px;" id="Submit1" ng-click="addNew()">REGISTER</button>
<table style="width:100%;">
<tr>
<th>UserId</th>
<th>Full Name</th>
</tr>
<tr ng-repeat="user in userDetails">
<td>
<input type="checkbox" ng-checked="user.selected" ng-model="editdeleteuserid" ng-click="selectEachCheckbox(user.userid)" />
</td>
<td>
{{user.userid}}
</td>
<td>
{{user.fullname | uppercase}}
</td>
</tr>
</table>
控制器:
//Each Checkbox Slection.
$scope.selectEachCheckbox = function (userid) {
$scope.selectAllCheckboxes = false;
var idx = selectedIds.indexOf(userid);
if (selectedIds.indexOf(userid) == -1) {
selectedIds.push(userid);
} else {
selectedIds.splice(idx, 1);
}
$scope.btnEditShowHide = false;
$scope.btnDelteHideShow = true;
if (selectedIds.length == 0){
$scope.btnDelteHideShow = false;
}
if(selectedIds.length == 1){
$scope.btnEditShowHide = true;
}
};
//Delete Click Button
$scope.DeleteUSers = function () {
var newDataList = $scope.userDetails;
for(i=0;i<selectedIds.length;i++){
var id = selectedIds[i];
var index = $scope.userDetails.indexOf(id)
$scope.userDetails.splice(index, 1);
}
$scope.userDetails = newDataList;
selectedIds = [];
$scope.selectAllCheckboxes = false;
};
答案 0 :(得分:4)
如果使用AngularJs的模型绑定功能,可以大大简化代码。
想法是使用ng-model
在数据数组内部记录复选框选择,删除过滤数据数组以清除所选项目。
angular.module('test', []).controller('Test', Test);
function Test($scope) {
$scope.items = [
{id: 1, name: 'apple'},
{id: 2, name: 'banana'},
{id: 3, name: 'orange'},
{id: 4, name: 'pear'}
];
$scope.delete = function() {
var deletedIds = $scope.items.filter(function(item) {
return item.selected;
}).map(function(item) {
return item.id;
});
$scope.deleted = "deleting id [" + deletedIds.join(",") + "]";
$scope.items = $scope.items.filter(function(item) {
return !item.selected;
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app='test' ng-controller='Test'>
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected" />
{{item.name}}
</div>
<button type="button" ng-click="delete()">delete</button>
<div>{{deleted}}</div>
</div>