Javascript 与<;选择ng选项="&引用/&燃气轮机;

Javascript 与<;选择ng选项="&引用/&燃气轮机;,javascript,angularjs,Javascript,Angularjs,我试图用AngularJS实现一个简单的特性,如下所示。在项目列表中,当用户单击某个项目并单击“删除”按钮时,该项目将被删除 html: 问题是,当我试图删除一个项目(即项目2)时,列表的第一个位置总是显示一个空项目。单击“项目1”或“项目3”时,空项目将消失 我知道这是由html中的ng model=“currentItem”引起的。currentItem指向要删除的项,currentItem指向null。因此,我更改了函数removietem,如下所示,以解决此问题 $scope.rem

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

html:

问题是,当我试图删除一个项目(即项目2)时,列表的第一个位置总是显示一个空项目。单击“项目1”或“项目3”时,空项目将消失

我知道这是由html中的
ng model=“currentItem”
引起的。currentItem指向要删除的项,currentItem指向null。因此,我更改了函数removietem,如下所示,以解决此问题

$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 */
    };
$scope.removietem=function(){
var index=$scope.items.indexOf($scope.currentItem);
$范围.项目.拼接(索引,1);
/*第一部分开始*/
如果($scope.items.length==0){
$scope.currentItem=null;
}否则{

如果(index>=0&&index,有一种简单的方法可以防止这种情况发生,那就是包含

 <option value="" ng-show="false"></option>

我以前也这样做过。我不知道还有更好的方法。你是否尝试在选择中添加ng if?就像
我尝试了ng if,但仍然是同一个问题。感谢解决方案。我注意到,当用户删除任何项目时,当前项目总是指向列表中的最后一个,而不加亮显示例如,如果我删除item1,看起来没有突出显示任何项目。但实际上item3是当前项目,当我再次单击“删除”按钮时,item3将被删除。
$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 */
    };
 <option value="" ng-show="false"></option>
<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>
$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];
};