我有一个简单的typeahead 用于货币列表。当我开始输入并选择所需的值(或按 TAB 键)时,所需的值将被选中 - 直到此时一切都按预期工作。
但是,如果我键入整个单词并单击输入框外而不是选择值(onblur 事件),那么即使输入框内的值与过滤器值匹配, selected 范围变量没有更新,所以我的输入无效。我想要做的是在 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>
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 也不要选择州),您会看到所选范围变量保持为空
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 - 使用 typeahead 时在 onblur 事件期间选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38070607/