Đây là cách bạn có thể làm điều đó:
app.factory('autoCompleteDataService', ['$http', function($http) {
return {
getSource: function() {
return function(request, response) {
$http.get(url).success(function(data) {
response(data);
});
}
}
}
}]);
Tuy nhiên, nếu bạn muốn tải toàn bộ dữ liệu đầu tiên và cho phép widget autocomplete để tìm kiếm dữ liệu trên các mặt hàng, đây là một ví dụ làm thế nào bạn có thể làm điều đó:
app.directive('autoComplete', function(autoCompleteDataService, $http) {
return {
restrict : 'A',
link : function(scope, elem, attr, ctrl) {
autoCompleteDataService.getData(function(err, data) {
if (err) {
console.log("Could not retrieve data.");
return;
}
elem.autocomplete({
minLength: 0,
source: data,
focus: function(event, ui) {
elem.val(ui.item.label);
return false;
},
select: function(event, ui) {
elem.val(ui.item.label);
return false;
}
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
});
}
};
});
app.factory('autoCompleteDataService', ['$http', '$rootScope', function($http, $scope) {
return {
getData: function(callback) {
if ($scope.data) {
return callback(null, $scope.data);
}
$http.get('URL')
.success(function(data) {
$scope.data = data;
return callback(null, data);
})
.error(function(data) {
return callback(true, null);
});
}
}
}]);
đã làm nó và bây giờ tôi nhận được "TypeError: this.source không phải là một chức năng" –
Bạn có thể thiết lập một ví dụ sau đó, vì tôi không biết làm thế nào bạn đang sử dụng $ hhtp dịch vụ – asgoth
tôi xin lỗi tôi đã có một typo, tôi đã sửa nó và bây giờ không có lỗi, nhưng cũng không có dữ liệu trả về. tôi sử dụng dịch vụ $ http chính xác như trong câu trả lời của bạn ở trên. –