3

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;
      })
    }
});
4

1 に答える 1

0

In the constructor for your controller, you can just set $scope.selectedItem to null if the value does not exist in the 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;
于 2014-10-08T13:38:16.847 に答える