我有以下代码通过对自动完成指令进行 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;
});
};
});
我正在尝试在自动完成源中使用承诺:因为 http 方法存在延迟,否则我会得到一个空数组。谁能告诉我如何使它工作?我不知道如何从 promise 函数中提取名称数组以传递给源: