是如何工作的,我有以下的代碼,通過在自動完成指令發送HTTP調用從服務器獲取用戶名:無法弄清楚承諾在角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方法有延遲,否則我會得到一個空數組。任何人都可以告訴我如何讓它工作?我不知道如何提取名稱陣列出來的諾言功能傳遞給源:
你必須[$超時](http://docs.angularjs.org /api/ng.$timeout)異步http請求..或懶惰加載它我想 – hunt