Reputation: 39
I have an issue at linking service having http to a directive. This is the code of that...
myapp.factory ( 'autoCompleteDataService', ['$http', function($http) {
return {
getSource: function(callback) {
var url = 'get_data_from_server.php';
$http.get(url).success(function(data) {
callback(data);
});
}
}
} ] );
myapp.directive('autoComplete', function(autoCompleteDataService) {
return {
restrict: 'A',
link: function(scope, elem, attr, ctrl) {
elem.autocomplete({
source: autoCompleteDataService.getSource(),
select: function( event, ui ) {
scope.$apply(function() {
scope.item.unit_id = ui.item.value;
});
},
minLength: 2
});
}
};
});
I replaced callback(data);
with return data;
with no result...
Any help is appreciated..
Edit: added working code without http
If I keep this code instead the above one its working
myapp.factory('autoCompleteDataService', [function() {
return {
getSource: function() {
return ['apples', 'oranges', 'bananas'];
}
}
}]);
Upvotes: 1
Views: 533
Reputation: 39
Another way to answer the issue,, with full filtering logic at server side..
myapp.directive('autoComplete', function(autoCompleteDataService) {
return {
restrict: 'A',
link: function(scope, elem, attr, ctrl) {
elem.autocomplete({
source: function( request, response ) {
$.ajax({
url: "./get_data_from_server.php",
dataType: "json",
data: {
maxRows: 10,
startsWith: request.term
},
success: function( data ) {
response(data);
}
});
},
select: function( event, ui ) {
scope.$apply(function() { scope.item.unit_id = ui.item.value; });
},
minLength: 2
});
}
};
});
Upvotes: 1
Reputation: 43947
myapp.factory('autoCompleteDataService', ['$http', function($http) {
return {
getSource: function() {
var url = 'get_data_from_server.php';
return $http.get(url);
}
}
}]);
Directive:
link : function(scope, elem, attr, ctrl) {
autoCompleteDataService.getSource().success(function(data) {
elem.autocomplete({
source: data,
select: function( event, ui ) {
scope.$apply(function() { scope.item.unit_id = ui.item.value; });
},
change: function (event, ui) {
if (ui.item === null) {
scope.$apply(function() { scope.foo = null });
}
},
minLength: 2
});
});
}
Upvotes: 0