您可以创建一个指令,使选择以您想要的方式运行。然后 HTML 将更改为:
<select clearable ng-model="selectedValue" ng-options="o.id as o.name for o in values"></select>
该指令的 JS 将是:
app.directive('clearable', ['$parse',function($parse){
return {
restrict : 'A',
scope : {
'ngModel' : '=',
'ngOptions' : '@'
},
require: ['select','?ngModel'],
link : function(scope, elem, attr,ctrl){
// Regex copied from the Angular Source
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
var match = scope.ngOptions.match(NG_OPTIONS_REGEXP);
var valuesFn = $parse(match[7]), //Options list
key = match[1].split('.')[1]; //Property in options list
scope.$watch(
function(){
// Watch for when the options list changes
return valuesFn(scope.$parent);
},
function(newList){
var isFound, i,
currentModelVal = scope.ngModel;
// Iterate through the new list to see if the current value is present
for(i=0;i<newList.length;i++){
if (newList[i][key] === currentModelVal){
isFound = true;
break;
}
}
// If not found, reset the ng-model value to null
if (!isFound){
ctrl[1].$setViewValue(null);
}
}
);
}
}
}]);
请参阅http://plnkr.co/edit/yAk9YSoMf88rtTqLXTiI?p=preview上的 Plunker