假设我在UI下定义如下降:设置NG选择下拉菜单模式为空时模型不NG选项存在
<select ng-model="selectedItem" ng-options="item as item.name for item in items track by item.id">
<option value="">Please select...</option>
</select>
和Controller:
$scope.items = [{name: 'item 1', id: 0}, {name: 'item 2', id: 1}];
$scope.selectedItem;
如果我将$scope.selectedItem
或模型设置为items数组中存在的值,例如{name: 'item 1', id: 1}
然后角预选'item 1'
这是预期的。
但是,如果我将模型设置为物品数组中不存在的虚假物品,例如$scope.selectedItem = {name: 'item 6', id: 6}
然后角预选'Please select...'
这是在UI中预期的,但该模型仍然是{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;
})
}
});
如果模型从* outside *设置为特定值,那么您将不得不在当时检查它是否是“正确”值或不。没有角糖可以帮助你。 – Yoshi 2014-10-08 13:53:35
您应该将答案放在答案中,而不是问题中。 – rightfold 2015-08-18 14:42:42