AngularJS预先调用web api

问题描述 投票:1回答:2

在这里使用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部分并将其推送到我的数组,然后我返回该数组。但是这个代码目前没有显示任何内容,没有错误。

我在这里错过了什么?

javascript angularjs typeahead
2个回答
1
投票

您错过了从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;
    });
};

2
投票

它应该是,

 typeahead="uName as uName.uName for uName in getUserNames($viewValue)" />
© www.soinside.com 2019 - 2024. All rights reserved.