编程语言
首页 > 编程语言> > javascript – 使用typeahead时在onblur事件期间选择值

javascript – 使用typeahead时在onblur事件期间选择值

作者:互联网

我有一个简单的预先输入货币列表.当我开始输入并选择所需的值(或点击TAB)时,会选择所需的值 – 直到这一点,一切都按预期工作.

但是,如果我输入整个单词并在输入外单击而不是选择值(onblur事件),那么即使输入中的值与过滤器值匹配,所选范围变量也不会更新,因此我的输入无效.我想要做的是在onblur事件期间覆盖选定的值.

示例:如果我在未点击TAB的情况下键入EUR或从typeahead下拉列表中选择EUR值,然后在输入外部单击,则EUR文本将保留在输入中,但所选值未定义.我希望所选值保持EUR而不是undefined.我使用$viewValue在onblur事件期间发送输入值.

HTML

<input type="text" ng-model="selected" typeahead-editable="false" typeahead="currency for currency in currencies | filter:$viewValue" ng-blur="selectCurrency($viewValue)" />
<div>Selected: {{selected}}</div>

JavaScipt:

angular.module('myApp', ['ui.bootstrap'])
.controller("mainCtrl", function ($scope) {
    $scope.selected = '';
    $scope.currencies = ['EUR', 'GBP', 'USD'];
    $scope.selectCurrency = function(test) {
        console.log(test); //outputs undefined instead of EUR
        //if (checkIfCurrencyExists(test, $scope.currencies)) { - will do the checks later
        $scope.selected = test;
        //}
    };
});

在下面的JsFiddle中,您可以看到相同的情况,除了它有美国州而不是货币.尝试输入Alabama,然后在输入外左键单击(不要选择并且不选择状态),您将看到所选范围变量保持为空

JsFiddle链接here.

解决方法:

找到另一种解决方案 – 将typeahead-select-on-exact和typeahead-select-on-blur属性设置为true:

   <input typeahead-select-on-exact="true" typeahead-select-on-blur="true" uib-typeahead=...

Typeahead-select-on-exact使得精确匹配的项目在列表中自动突出显示,而typeahead-select-on-blur使得在模糊时选择高亮项目.

标签:javascript,angularjs,angular-ui-bootstrap,bootstrap-typeahead
来源: https://codeday.me/bug/20190706/1394889.html