AngularJS typeahead calling webapi



在这里使用 AngularJS 和 C# webapi。

我正在创建一个输入控件,当用户开始在其中键入时,我想使用 typeahead 并显示返回的数据。

我已经设置了以下类型:

.HTML:

<input type="text" name="uName" ng-model="uName" autocomplete="off" required class="form-control input-medium" placeholder="Enter user name..."
typeahead="uName for uName in getUserNames($viewValue)" />

控制器:

$scope.getUserNames = function (search) {
myService.getUserNamesFromApi(search).then(function (response) {
$scope.foundNames = [];
if (response.length > 0) {
for (var i = 0; i < response.length; i++) {
$scope.foundNames.push({ 'uName': response[i].uName });
}
return $scope.foundNames;
}
});
};

从我的 API 返回的数据是一个数组,例如:

0: {fName: "Adam", lName: "Smith", uName: "asmith123"},
1: {fName: "John", lName: "Bambi", uName: "jbambi456"}

等等...

我正在尝试获取 uName 部分并将其推送到我的数组,然后返回该数组。但是目前使用此代码,它什么也没显示,没有错误。

我在这里错过了什么?

它应该是,

typeahead="uName as uName.uName for uName in getUserNames($viewValue)" />

您错过了从getUserNames函数返回承诺。这就是 typeahead 加载异步集合的方式,只要您键入某些内容。并且还从外部返回$scope.foundNames;if条件。

$scope.getUserNames = function (search) {
// return promise here.
return myService.getUserNamesFromApi(search).then(function (response) {
$scope.foundNames = [];
if (response.length > 0) {
for (var i = 0; i < response.length; i++) {
$scope.foundNames.push({ 'uName': response[i].uName });
}
}
// return result from here.
return $scope.foundNames;
});
};

最新更新