我有一个 AngularJS Typeahead 异步检索匹配项。当条码被扫描到字段中时,它会返回匹配结果,但用户仍然必须选择它。如果结果完全匹配,我想自动选择结果。我看到 typeahead 有一个 select(idx) 函数,但我不确定如何从我的 Controller 获取对它的引用。
我在设想这样的事情:
$scope.SearchItems = function (term) {
return $http.get('api/Items/Search', {
params: {
term: term
}
}).then(function (response) {
if (response.data.length == 1 && response.data[0].Code == term) {
// Somehow inform typeahead control to select response.data[0]
}
return response.data;
});
};
最佳答案
我遇到了类似的问题,但从未想过如何访问预先输入的 select(idx)
,但我设法使此功能正常工作。这是我的hacky解决方法....
$promise.then(function(res) {
angular.forEach(res, function(item, key) {
// if we have an exact match
if (item.title === term) {
// update model
$scope.src = item;
// find item in dropdown
var elm = '[id*=option-' + key + ']';
var opt = angular.element(document.querySelectorAll(elm));
//call click handler outside of digest loop
$timeout(function() {
opt.triggerHandler('click');
}, 0);
}
});
// return async results
return res;
});
基本上我们只是手动更新我们的模型,在我们的下拉列表中找到元素,然后触发“点击”处理程序。确保将
triggerHandler
包裹起来调用 $timeout()
设置为零,否则你会得到一个 $rootScope:inprog
错误,因为摘要已经在进行中。
关于angularjs - 以编程方式选择 AngularJS Typeahead 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27337411/