2015-05-13 24 views
3

問題我嘗試使用AngularJS實現一個簡單的功能,如下所示。在項目列表中,當用戶單擊一個項目並單擊刪除按鈕時,該項目將被刪除。<select ng-options =「...」/>

enter image description here

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」時,空的項目消失。

enter image description here

我知道,這是由ng-model="currentItem"在HTML所致。 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部分的動作。

+0

我以前做過這個。我不知道更好的方法。 – z0r

+0

您是否嘗試在選擇中添加ng-if?比如'' –

+0

我試過如果它仍然是同樣的問題。 – yyou

回答

4

有在其中您可以阻止簡單的辦法就是包括

<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> 

Working Demo

更新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]; 
}; 

Working Demo

+0

感謝您的解決方案。有一件事我注意到,當用戶刪除任何項目時,currentItem總是指向列表中的最後一個,而不突出顯示它。例如,如果我刪除item1,它看起來沒有項目突出顯示。但實際上item3是當前項目,當我再次點擊'刪除'按鈕時,item3被刪除。 – yyou

+0

@yyou看看我的更新 –