综合开发

Value Typeahead in Bootstrap UI

微信扫一扫,分享到朋友圈

Value Typeahead in Bootstrap UI

I’m working on an app using AngularJS and Bootstrap UI. I’ve been fumbling my way through using the Typeahead control in Bootstrap UI.


Here’s my Plunker

My challenge is I want the user to have the option of choosing an item, but not required to do so. For instance, right now, if you type Test
in the text field and press “Enter”, Test
will be replaced with Alpha
. However, I really want to use Test
. The only time I want the text to be replaced is when someone chooses the item from the drop down list. My markup looks like the following:

<input type="text" class="form-control" placeholder="Search..."
ng-model="query"
typeahead="result as result.name for result in getResults($viewValue)"
typeahead-template-url="result.html" />

How do I give the user the option of choosing an item, but allow them to still enter their own text?

I came across this same situation and found no good answers so I implemented it myself in ui-bootstrap
Here is the relevant answer. This is probably not the best route to take, but it does get the job done. It makes the first result in the typeahead to be what you’re currently typing, so if you tab or enter off of it, it’s selected — you must arrow-down or select another option to get it.

Here
is the modified ui-bootstrap-tpls.js
file

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-arrow-down-to-match="true">

And the javascript:

var mustArrowDownToMatch = originalScope.$eval(attrs.typeaheadArrowDownToMatch) ? originalScope.$eval(attrs.typeaheadArrowDownToMatch) : 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
});
}

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 (mustArrowDownToMatch) {
setFirstResultToViewValue(inputValue);
scope.activeIdx = 0;
setTypeaheadPosition();
}
// do stuff
};

天猫国际:跨境消费正呈现普及化趋势

上一篇

抗击肺炎疫情 索尼追加捐款至3000万日元

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

Value Typeahead in Bootstrap UI

长按储存图像,分享给朋友