使用提前输入时,在onblur事件期间选择值

Too*_*nia 6 javascript angularjs bootstrap-typeahead angular-ui-bootstrap

我可以简单输入一个货币列表。当我开始键入内容并选择所需的值(或按TAB键)时,即会选择所需的值-直到此时一切都按需工作。

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

示例:如果我键入EUR而不点击TAB或从预输入下拉列表中选择EUR值,然后在输入之外单击,则EUR文本停留在输入内部,但所选值未定义。我希望所选的值保留EUR而不是未定义。我使用$ 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>
Run Code Online (Sandbox Code Playgroud)

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;
        //}
    };
});
Run Code Online (Sandbox Code Playgroud)

在下面的JsFiddle中,您可以看到相同的场景,除了它具有美国州而不是货币。尝试输入阿拉巴马州,然后在输入之外单击鼠标左键(不要选择Tab键,也不要选择状态),您会看到所选范围变量保持为空

JsFiddle链接在这里

Too*_*nia 1

当时我自己找到了答案,但忘记在这里回答我的问题。

将其添加到指令中:

data-ng-blur="blur($event)"
Run Code Online (Sandbox Code Playgroud)

这是函数:

$scope.blur = function(e) {
            var inputCurrency = e.target.value.toUpperCase();
            angular.forEach($scope.currencies, function(currency) {
                if (currency === inputCurrency) {
                    $scope.field = currency;
                }
            });
        };
Run Code Online (Sandbox Code Playgroud)