为什么自动完成输入不能正确更新模型? [英] Why is an Autocomplete input not updating the model correctly?
问题描述
我正在使用以下依赖项:
I'm using the following dependencies:
- angularJS v1.5.5
- jquery v1.12.4
- jquery-ui v1.12.1
- jQuery 自动完成插件v1.2.6
- angularJS v1.5.5
- jquery v1.12.4
- jquery-ui v1.12.1
- jQuery Autocomplete plugin v1.2.6
然后我像这样定义指令:
I then define the directive like this:
.directive('autoComplete', [
'$timeout', function($timeout) {
return function(scope, element, attrs) {
var auto;
auto = function() {
$timeout((function() {
if (!scope[attrs.uiItems]) {
auto();
} else {
element.autocomplete({
source: [scope[attrs.uiItems]]
});
}
}), 0);
};
return auto();
};
}
])
which I borrowed from the answer to this SO question. The autocomplete works for the most part but when I move across the matches with the keyboard and press return or click on the match with the mouse, the model is updated with only the part that I typed and not with the full item selected. Where should I look to fix this? is it a bug in the plugin? directive? my input definition?
$scope.ccyPairs = [ "USDCHF", "CHFUSD", "USDEUR", "EURUSD", "USDGBP", "GBPUSD", "USDJPY", "JPYUSD", "CHFEUR", "EURCHF", "CHFGBP", "GBPCHF", "CHFJPY", "JPYCHF", "EURGBP", "GBPEUR", "EURJPY", "JPYEUR", "GBPJPY", "JPYGBP" ];
<input type="text" auto-complete id="ccyPair" ui-items="ccyPairs" ng-model="ccyPair" />
当我这样做时:
$scope.$watch("ccyPair", function(newValue, oldValue) {
console.log(newValue);
}, false);
我看到只用我输入的部分更新了模型,而不用列表中的完整选定匹配项进行更新,要么用鼠标单击选择它,要么在匹配项上移动并按Enter.
I see that the model is updated only with the part that I type in the input and not with the full selected match in the list either selecting it with a mouse click or moving across the matches and pressing enter.
例如,在下面的图片中,模型仅更新为USD
,而没有更新为正确的完全匹配CHFUSD
.
For example, in the picture below, the model is updated to USD
only and not to the correct full match CHFUSD
.
推荐答案
好吧,在经历了很多痛苦之后,我爬上了可行的解决方案:)
OK after a lot of agony I crawled my way into a working solution :)
.directive('autoComplete', [
'$timeout', function($timeout) {
return {
require: 'ngModel',
link: function($scope, element, attrs, ctrl) {
var fAutoComplete;
fAutoComplete = function() {
$timeout(function() {
if (!$scope[attrs.uiItems]) {
fAutoComplete();
} else {
element.autocomplete({
source: [$scope[attrs.uiItems]]
}).on('selected.xdsoft', function(e, newValue) {
ctrl.$setViewValue(newValue);
$scope.$apply();
});
}
}, 5);
};
return fAutoComplete();
}
};
}
])
这篇关于为什么自动完成输入不能正确更新模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!