Angular 异步 http 自动完成

Angular async http autocomplete

我想用 Angular 创建一个自动完成,因为这是我第一次接触 angular,所以我很困惑。

这是我的代码:

 MenuService.getAutocompleteData(term).then(function (response) {
            $scope.menuData = response.data;
        });

这就是我调用进行以下 http 调用的服务的方式:

return $http({
            url    : autocompletePath,
            method : "POST",
            data   : {
                term: term
            }
        }).success(function (response) {
            return response;
        });

问题是它似乎是同步的,当我键入快速字母时我的浏览器死机了。我看到这是关于“.then”的承诺,但我不确定如何解决它。任何帮助,将不胜感激。

你做了一个 HTTP 请求,这是正确的,但你尝试 return 成功的结果。相反,您应该尝试在成功处理程序中完成需要完成的工作。

所以在你的服务中你会做这样的事情:

    return $http({
        url    : autocompletePath,
        method : "POST",
        data   : {
            term: term
        }
    }); //note that there is no success handler in your service, because what's supposed to happen when the request completes, is the controller's business, not the service's. The service should only know where to get the data

你会把你的控制器改成这样:

  MenuService.getAutocompleteData(term).success(function (response) {
        $scope.menuData = response.data;
    }); //note the success-handler

你为什么不试一试呢? https://angular-ui.github.io/bootstrap/#/typeahead