2014-10-08 43 views
3

假設我在UI下定義如下降:設置NG選擇下拉菜單模式爲空時模型不NG選項存在

<select ng-model="selectedItem" ng-options="item as item.name for item in items track by item.id"> 
    <option value="">Please select...</option> 
</select> 

和Controller:

$scope.items = [{name: 'item 1', id: 0}, {name: 'item 2', id: 1}]; 
$scope.selectedItem; 

如果我將$scope.selectedItem或模型設置爲items數組中存在的值,例如{name: 'item 1', id: 1}然後角預選'item 1'這是預期的。

但是,如果我將模型設置爲物品數組中不存在的虛假物品,例如$scope.selectedItem = {name: 'item 6', id: 6}然後角預選'Please select...'這是在UI中預期的,但該模型仍然是{name: 'item 6', id: 6}

對於一個虛構物品的例子,是否有角度設置模型$scope.selectedItemnull而不是{name: 'item 6', id: 6}

在我的情況下,$scope.selectedItem對象正在保存到數據庫,所以在將來加載它時,我不能保證該對象將存在於$scope.items陣列中。如果該對象不再存在於數組中,我希望angular將模型設置爲null,而不是保留陳舊的對象。

明顯的解決方案是檢查數組中是否存在對象,如果不存在,請在控制器中手動設置$scope.selected = null,但希望查看是否有更簡單或更簡潔的選項。

解決方案:

選擇使用一個指令:

.directive('checkForNull', function() { 
    return { 
    link: function (scope, element, attrs) { 
     scope.$watchCollection('items', function(value){ 
     // if $scope.selectedItem does not exist in items array (value) 
     $scope.selectedItem = null; 
     }) 
    } 
}); 
+0

如果模型從* outside *設置爲特定值,那麼您將不得不在當時檢查它是否是「正確」值或不。沒有角糖可以幫助你。 – Yoshi 2014-10-08 13:53:35

+0

您應該將答案放在答案中,而不是問題中。 – rightfold 2015-08-18 14:42:42

回答

0

在構造你的控制器,你可以設置$ scope.selectedItem如果該值不存在的爲空items array:

$scope.items = [{name: 'item 1', id: 0}, {name: 'item 2', id: 1}]; 
$scope.selectedItem = ($scope.items.indexOf($scope.selectedItem) !== -1) ? $scope.selectedItem : null; 
+0

在我的情況下,模型被持久化到數據庫。當'$ scope.selectedItem'值設置爲數據庫中的對象時,對象可能不再存在於items數組中 – jodev 2014-10-08 13:49:17

+0

我已更新答案,以便將值設置爲null,如果該值不存在於items數組中。 – Martin 2014-10-08 13:54:30