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

查看:128
本文介绍了使用提前输入时,在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事件),那么即使我输入中的值与过滤器值匹配,选择作用域变量不会更新,因此我的输入无效.我想做的是在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 文本停留在输入中,但是所选值为 undefined .我希望所选的值保留EUR而不是未定义.我在onblur事件期间使用 $ viewValue 发送输入值.

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:

The 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中,您可以看到相同的场景,除了它具有美国州而不是货币.尝试输入阿拉巴马州,然后在输入内容之外单击鼠标左键(不要按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;
                }
            });
        };

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

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