我在指令中实现了以下预输入代码。
这是 HTML:
<div>
<input type="text"
ng-model="company"
uib-typeahead="company as company.name for company in companyByName($viewValue)"
typeahead-loading="loadingCompanies"
typeahead-no-results="noCompanyResults"
class="form-control">
<i ng-show="loadingCompanies" class="glyphicon glyphicon-refresh"></i>
<div ng-show="noCompanyResults">
<i class="glyphicon glyphicon-remove"></i> No Results Found
</div>
</div>
这是 JavaScript:
scope.companyByName = function() {
var companyName = scope.company.name ? scope.company.name : scope.company;
var searchTerms = {name: companyName, startRow: 0, endRow: 20};
return $http.post("backend/get/companies.php", searchTerms).then((result) => {
$log.info("Companies", result.data.results);
return result.data.results;
});
};
PHP 代码 backend/get/companies.php
接受搜索字符串并返回具有 id
和 name
属性的对象数组包含该搜索字符串的名称。
这是我遇到的行为:
当我在预输入字段中键入单个字符“f”时,传递给后端脚本的 companyName
的值为“”(空字符串)。 backend/get/companies.php
返回所有结果。
当我在预输入字段中键入第二个字符“fo”时,传递给后端脚本的 companyName
的值为“f”。 backend/get/companies.php
返回匹配“f”的结果。
键入第三个字符“foo”会返回匹配“fo”等的结果。
我已经根据 official examples 对我的代码进行了建模.到底是怎么回事?我的感觉是 companyByName()
函数以某种方式被在字符输入输入之前触发的事件调用。有什么想法吗?
最佳答案
问题是 ng-model 落后于 View 值。当调用 companyByName
时,ng-model 不会更新为输入字段中的最新值。要从输入中获取最新值,您应该使用传递给 companyByName
函数的参数:
scope.companyByName = function(viewValue) {
var searchTerms = {name: viewValue, startRow: 0, endRow: 20};
return $http.post("backend/get/companies.php", searchTerms).then((result) => {
$log.info("Companies", result.data.results);
return result.data.results;
});
};
关于javascript - 具有异步加载的 Angular bootstrap typeahead 落后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33742887/