问题
I've created this jsBin to demonstrate the issue I'm having. If you go here, try type "Five" and move on. Your natural reaction would be to type "Five" and then press tab, and if you wanted "Five-Hundred," you'd arrow-down once; however, in this case, you have to type "Five" and then either press escape or physically mouse out of the box without clicking any of the other options
So, basically, when you're using typeahead, if there is at least one matching result for your current criteria, pressing tab will select it. My expected behavior is that as you type, the current selected option is exactly what you're typing, and if you want one of the other results you must down-arrow one or more times.
Here is the code that's in the jsBin:
<div ng-controller="TestController">
<div>
{{selected}}
</div>
<input type="text" ng-model="selected" typeahead="item for item in typeaheadOptions | filter:$viewValue">
</div>
And the JavaScript:
var app = angular.module('app', ['ui.bootstrap'])
.controller('TestController', function($scope) {
$scope.typeaheadOptions = [
'One','Two','Three','Four','Five-Hundred','Fifteen','Fourteen','Fifty','Six','Seven','Eight','Nine','Ten'
]
});
回答1:
I ended up modifying ui-bootstrap
to work how I want it to.
I added a mustMouseDownToMatch
property/attribute to the directive, like:
<input type="text" ng-model="selected" typeahead="item for item in typeaheadOptions | filter:$viewValue" typeahead-mouse-down-to-match="true">
And the javascript:
var mustMouseDownToMatch = originalScope.$eval(attrs.typeaheadMouseDownToMatch) ? originalScope.$eval(attrs.typeaheadMouseDownToMatch) : false;
I also added this function which will put the current text into the first item of the typeahead list, and make it the selected item:
var setFirstResultToViewValue = function (inputValue) {
scope.matches.splice(0, 0, {
id: 0,
label: inputValue,
model: inputValue
});
// set the selected item to the first item in the list, which is this guy
scope.activeIdx = 0;
}
And that is called in the getMatchesAsync
call in the typeahead directive:
var getMatchesAsync = function(inputValue) {
// do stuff
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
// do stuff
if (matches.length > 0) {
// do stuff
}
if (mustMouseDownToMatch) {
setFirstResultToViewValue(inputValue);
}
// do stuff
};
来源:https://stackoverflow.com/questions/23698497/tab-off-ui-bootstrap-typeahead-only-when-row-is-explicitly-selected