当ng-options中不存在模型时,将选择下拉模型设置为null

时间:2014-10-08 13:26:37

标签: angularjs angularjs-ng-options

假设我在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或模型设置为items数组中存在的值,例如{name: 'item 1', id: 1}然后angular预选'item 1',这是预期的。

但是,如果我将模型设置为项目数组中不存在的虚假项目,例如$scope.selectedItem = {name: 'item 6', id: 6}然后angular预选了UI中预期的'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;
      })
    }
});

1 个答案:

答案 0 :(得分:0)

在控制器的构造函数中,如果items数组中不存在该值,则可以将$ scope.selectedItem设置为null:

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