您可以添加ng-required
到选择。如果模型没有初始值,则将添加一个空选项,并在更改为有效值时删除该空选项
编辑 jsFiddle 以恢复到以前的值并包含ng-change指令。
从文档:
当值更改来自模型时,不会评估表达式。
这对于不干扰更改侦听器并在恢复$apply
函数中的旧值时创建无限循环很有用
控制器
$scope.options = [{value: 'abc'},{value: 'def'}];
var confirmDialog = function(newVal, yes, no) {
// obviously not a good way to ask for the user to confirm
// replace this with a non blocking dialog
//the timeout is only for the confirm since it's blocking the angular $digest
setTimeout(function() {
c = confirm('Is it ok? [' + newVal.value + ']');
if(c) {
yes();
}
else {
no();
}
}, 0);
};
//Asking for confirmation example
function Ctrl($scope) {
$scope.options = [{value: 'abc'},{value: 'def'}];
$scope.select = undefined;
var oldSelect = undefined;
$scope.confirmChange = function(select) {
if(oldSelect) {
confirmDialog(select,
function() {
oldSelect = select;
},
function() {
$scope.$apply(function() {$scope.select = oldSelect;});
});
}
else {
oldSelect = select;
}
}
}
模板
<div ng-controller="Ctrl">
<select ng-model="select" ng-options="o.value for o in options"
ng-required ng-change="confirmChange(select)">
</select>
</div>