我目前正在实现一个Angular typeahead,每次用户更改输入时都会从API中提取数据。如果我添加typeahead-wait-ms=200
,则预先输入正确。如果我不这样做,我会收到错误length of undefined.
这是代码:
HTML
<input type="text" ng-model="selectedUser" typeahead="user for user in userTypeAhead($viewValue)">
的JavaScript
$scope.userTypeAhead = function(userTypeAheadInput){
myService.searchUserTypeAhead(userTypeAheadInput).then(function(data) {
$scope.userTypeAheadResults = [];
for (i = 0; i < data.array.length; i++) {
$scope.userTypeAheadResults.push(data.array[i].userName);
}
return $scope.userTypeAheadResults;
}, function(error) {
console.log(error)
});
}
当代码通过时,$scope.userTypeAheadResults
返回将在typeahead中显示的userNames数组。数组返回正确,但在函数返回之前,错误已在控制台中显示length of undefined
。我在stackoverflow上看了几个其他的问题,没有运气。有任何想法吗?
提前谢谢。
答案 0 :(得分:2)
回报承诺。
$scope.userTypeAhead = function(userTypeAheadInput){
// return the promise
return myService.searchUserTypeAhead(userTypeAheadInput).then(function(data) {
$scope.userTypeAheadResults = [];
for (i = 0; i < $scope.data.array.length; i++) {
$scope.userTypeAheadResults.push(data.array[i].userName);
}
return $scope.userTypeAheadResults;
}, function(error) {
console.log(error)
});
}