AngularJS提前调用webapi

时间:2018-09-13 17:38:21

标签: javascript angularjs typeahead

在此处使用带有C#webapi的AngularJS。

我正在创建一个输入控件,当用户开始输入该控件时,我想使用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部分并将其推入我的数组,然后返回该数组。但是目前使用此代码,它什么也不显示,没有错误。

我在这里想念什么?

2 个答案:

答案 0 :(得分:2)

应为

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

答案 1 :(得分: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;
    });
};