Angularjs 当ng选项中不存在模型时,将ng select下拉列表模型设置为null
假设我在UI中定义了以下下拉列表:Angularjs 当ng选项中不存在模型时,将ng select下拉列表模型设置为null,angularjs,angularjs-ng-options,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.selectedItem或模型设置为项目数组中存在的值,例如{name:'item
<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.selectedItem
或模型设置为项目数组中存在的值,例如{name:'item 1',id:1}
,则角度预选'item 1'
,这与预期一致
但如果我将模型设置为项数组中不存在的伪项,例如$scope.selectedItem={name:'item 6',id:6}
,则角度预选'Please select…'
,这是UI中所期望的,但模型仍然保持{name:'item 6',id:6}
对于带有伪项的示例,angular是否仍可以将模型$scope.选择EdItem
设置为null
,而不是{name:'item 6',id:6}
在我的例子中,$scope.selectedItem
对象正在保存到数据库中,因此将来加载时,我无法保证该对象将存在于$scope.items
数组中。如果数组中不再存在该对象,我希望将模型设置为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;
})
}
});
在控制器的构造函数中,如果项数组中不存在该值,则可以将$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;
在我的情况下,模型被持久化到数据库中。如果将
$scope.selectedItem
值设置为数据库中的对象,则该对象可能不再存在于items数组中。如果items数组中不存在该值,我已更新答案以将该值设置为null。如果模型从外部设置为特定值,则此时您必须检查该值是否为空“正确”与否。这里没有角糖可以帮助你。你应该把答案放在答案中,而不是问题中。
$scope.items = [{name: 'item 1', id: 0}, {name: 'item 2', id: 1}];
$scope.selectedItem = ($scope.items.indexOf($scope.selectedItem) !== -1) ? $scope.selectedItem : null;