jkn*_*rkn 6 javascript php angularjs angular-ui-typeahead angular-bootstrap
我在一个指令中实现了以下类型的代码.
这是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>
Run Code Online (Sandbox Code Playgroud)
这是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;
});
};
Run Code Online (Sandbox Code Playgroud)
PHP代码backend/get/companies.php接受一个搜索字符串并返回与对象的数组id和name与包含该搜索字符串名称属性.
以下是我遇到的行为:
当我在typeahead字段中键入单个字符"f"时,companyName传递给后端脚本的值为""(空字符串).backend/get/companies.php返回所有结果.
当我在typeahead字段中键入第二个字符"fo"时,companyName传递给后端脚本的值为"f". backend/get/companies.php返回与"f"匹配的结果.
键入第三个字符"foo"将返回与"fo"等匹配的结果.
我在官方示例之后建模了我的代码.到底是怎么回事?我的感觉是,companyByName()某个函数被一个事件调用,该事件在字符输入输入之前触发.有什么想法吗?
问题是 ng-model 落后于视图值。当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;
});
};
Run Code Online (Sandbox Code Playgroud)