Set ng select dropdown model to null if model doesn't exist in ng-options

Suppose I have defined the following snapshot in the 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>

      

And in the controller:

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

      

If I set $scope.selectedItem

or model to a value that exists in an array of elements, eg. {name: 'item 1', id: 1}

then angular prefetches 'item 1'

which is as expected.

But if I set the model to a dummy item that doesn't exist in the item array eg. $scope.selectedItem = {name: 'item 6', id: 6}

then angular preselects 'Please select...'

, which is expected in the UI, but the model still remains {name: 'item 6', id: 6}

.

For the dummy element example, is there anyway for angular to set the model $scope.selectedItem

to null

instead of {name: 'item 6', id: 6}

?

In my case, the object is $scope.selectedItem

stored in the database, so when it is loaded in the future, I cannot guarantee that the object will exist in the array $scope.items

. If the object no longer exists in the array, I would like angular to set the model to null instead of storing the deprecated object.

The obvious solution is to check if the object exists in the array, and if not, set it $scope.selected = null

manually in the controller, but want to check if there is a simpler or cleaner option.

Decision:

Refused to use directive:

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

      

+3


source to share


1 answer


In the constructor for your controller, you can simply set the value of $ scope.selectedItem to null if the value doesn't 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;

      

0


source







All Articles