UI で次のドロップダウンを定義したとします。
<select ng-model="selectedItem" ng-options="item as item.name for item in items track by item.id">
<option value="">Please select...</option>
</select>
そしてコントローラーで:
$scope.items = [{name: 'item 1', id: 0}, {name: 'item 2', id: 1}];
$scope.selectedItem;
$scope.selectedItem
たとえば、アイテム配列に存在する値にモデルを設定すると、期待どおりの{name: 'item 1', id: 1}
角度が事前選択'item 1'
されます。
しかし、アイテム配列に存在しない偽のアイテムにモデルを設定すると、たとえば、UI で予期される$scope.selectedItem = {name: 'item 6', id: 6}
角度の事前選択が行われますが、モデルは残ります。'Please select...'
{name: 'item 6', id: 6}
偽のアイテムの例では、角度の代わりにモデル$scope.selectedItem
を設定する方法はありますか?null
{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;
})
}
});