在这里使用AngularJS和C#web api。
我正在创建一个输入控件,当用户开始输入它时,我想使用typeahead并显示返回的数据。
我已经设置了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部分并将其推送到我的数组,然后我返回该数组。但是这个代码目前没有显示任何内容,没有错误。
我在这里错过了什么?
您错过了从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;
});
};
它应该是,
typeahead="uName as uName.uName for uName in getUserNames($viewValue)" />