2016-05-25 12 views
0

現在、ユーザーが入力を変更するたびにAPIからデータを引き出すAngular型の先頭を実装しています。私がtypeahead-wait-ms=200を追加すると、先読みは正しく機能します。私はないと、私はここでlength of undefined.のエラーコードで取得する:$scope.userTypeAheadResults、コードが通過するときAPIコールが返される前に角型先読みが返され、「長さ不定」エラーが発生する

<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) 
    }); 
} 

HTMLユーザ名の配列を返すことでしょう前向きに見せてください。配列は正しく返されますが、関数が返される前に、エラーは既にコンソールにlength of undefinedと表示されています。私はここでstackoverflowの他のいくつかの質問を見て、運がなかった。何か案は? ありがとうございます。

+0

なぜあなたの状態は$ scope.data.array.lengthを保持していますか? data.array.lengthではなく? – WalksAway

+0

申し訳ありません、それはdata.array.lengthです。私の間違い。 – Jaromjj

答えて

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) 
    }); 
} 
関連する問題