使用 typeahead 时在 onblur 事件期间选择值 [英] Select value during onblur event when using typeahead

查看:27
本文介绍了使用 typeahead 时在 onblur 事件期间选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的预先输入,用于显示货币列表.当我开始输入并选择所需的值(或按 TAB 键)时,将选择所需的值 - 直到此时一切都按预期工作.

I have a simple typeahead for a list of currencies. When I start typing and I select the desired value (or hit TAB on that), the desired value is selected - until this point everything works as desired.

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

However, if I type the entire word and click outside the input instead of selecting the value (onblur event), then even if the value inside my input matches the filter value, the selected scope variable doesn't update, so my input is invalid. What I'm trying to do is to overwrite the selected value during onblur event.

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

Example: If I type EUR without hitting TAB or selecting the EUR value from the typeahead dropdown and then click outside the input, the EUR text stays inside the input, but selected value is undefined. I want the selected value to hold EUR instead of undefined. I used $viewValue to send the input value during onblur event.

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 然后在输入外左键单击(不要 TAB 也不要选择状态),您将看到所选范围变量保持为空

In the JsFiddle below you can see the same scenario, except it has US states instead of currencies. Try to type in Alabama then left click outside the input (don't TAB and don't select the state), you'll see that the selected scope variable stays empty

JsFiddle 链接这里.

JsFiddle link here.

推荐答案

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

Found an answer myself at the time, but forgot to answer my question here.

将此添加到指令中:

data-ng-blur="blur($event)"

这是函数:

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

这篇关于使用 typeahead 时在 onblur 事件期间选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆