我试着用AngularJS实现一个简单的特性,如下所示。在项目列表中,当用户单击某个项目并单击删除按钮时,该项目将被删除。

html:
<div ng-app="app" ng-controller="MainController">
<div>
<select ng-options="item.name for item in items" ng-model="currentItem" size="5" style="width: 200px"></select>
</div>
<button ng-click="removeItem()">Remove</button>
</div>脚本如下:
angular.module('app', [])
.controller('MainController', function($scope) {
$scope.items = [{
name: 'item1'
}, {
name: 'item2'
}, {
name: 'item3'
}];
$scope.currentItem = $scope.items[0];
$scope.removeItem = function() {
var index = $scope.items.indexOf($scope.currentItem);
$scope.items.splice(index, 1);
};
});问题是,当我试图删除一个项目(即item2)时,列表总是在第一个位置显示一个空项目。当我点击'item1‘或'item3’时,空的项目消失了。

我知道这是由html中的ng-model="currentItem"引起的。currentItem指向要删除的项,currentItem指向null。所以我修改了函数removeItem,如下所示来解决这个问题。
$scope.removeItem = function() {
var index = $scope.items.indexOf($scope.currentItem);
$scope.items.splice(index, 1);
/* PART 1 begin */
if ($scope.items.length === 0) {
$scope.currentItem = null;
} else {
if (index >= 0 && index <= $scope.items.length - 1) {
$scope.currentItem = $scope.items[index];
} else {
$scope.currentItem = $scope.items[$scope.items.length - 1];
}
}
/* PART 1 end */
};我想知道在AngularJS中是否有任何简单的方法(如指令)来自动完成第1部分中的操作。
发布于 2015-05-13 20:46:47
有一种简单方法可以防止这种情况,只需包含
<option value="" ng-show="false"></option>在如下所示select like中
<select ng-options="item as item.name for item in items" ng-model="currentItem" size="5" style="width: 200px">
<option value="" ng-show="false"></option>
</select>更新1
我已经解决了不突出显示最后一项的问题,请看一下工作演示
$scope.removeItem = function () {
var index = $scope.items.indexOf($scope.currentItem);
$scope.items.splice(index, 1);
index === $scope.items.length ? $scope.currentItem = $scope.items[index - 1] : $scope.currentItem = $scope.items[index];
};https://stackoverflow.com/questions/30214831
复制相似问题