无法弄清楚promises如何在角度http中工作

时间:2013-07-11 18:03:36

标签: angularjs autocomplete promise

我有以下代码,通过在自动完成指令上进行http调用来从服务器检索用户名:

var app2 = angular.module('MyModule', []);

app2.directive('autoComplete', function ($timeout) {
    return function (scope, iElement, iAttrs) {
        iElement.autocomplete({
            source: function () {
                //can't call this like so: scope.$apply('getSource'); I get "$apply already in progress error"
                var names = scope.getSource();
                scope.$apply();
                console.log(names);
                return names;
            },
            async:false,
            minLength: 3,
            select: function () {
                $timeout(function () {
                    iElement.trigger('input');
                }, 0);
            }
        });
    };
});

app2.controller('DefaultCtrl', function($scope, $http) {
    $scope.getSource = function() {
        return $http.get('/AccountRequest/GetMatchingEmployeeNames?matchStr=' + $scope.selected)
            .then(function (data) {
                var names = [];
                for (var i = 0; i < data.length; i++) {
                    names.push(data[i].Name);
                }
                return names;
            });
    };
});

我正在尝试在自动完成源中使用一个promise:因为http方法有一个延迟,否则我得到一个空数组。请问有谁可以告诉我如何才能使它发挥作用?我不知道如何从promise函数中提取names数组以传递给source:

1 个答案:

答案 0 :(得分:0)

source: function (request,responseCallback) {
            var names = [];
            var promise = scope.getSource();
            promise.success(function(data){
                names = data;
                console.log(names);
                responseCallback(names);
            }).error(function() {
                console.log("some error occurred");
                responseCallback(names);
            });
        },

或者

source: function (request,responseCallback) {
            var names = [];
            var promise = scope.getSource();
            promise.then(function(data){
                names = data;
                console.log(names);
                responseCallback(names);
            },function() {
                console.log("some error occurred");
                responseCallback(names);
            });
        },

我是根据jQuery自动完成文档编写的,该文档说源代码传递了一个传递请求和响应回调函数的函数。

详细了解承诺如何在此处运作:http://docs.angularjs.org/api/ng.$q

详细说明如何为$ http服务http://docs.angularjs.org/api/ng.$http

进行扩展