Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs autocomplete from $http

I'm trying to write an autocomplete directive that fetches data from the server using an $http request (without using any external plugins or scripts). Currently it works only with static data. Now, I know that I need to insert my $http request into the source: of the directive, but I can't find any good documentation on the subject.

http request

$http.post($scope.url, { "command": "list category() names"}).              success(function(data, status) {                 $scope.status = status;                 $scope.names = data;                 })             .             error(function(data, status) {                 $scope.data = data || "Request failed";                 $scope.status = status;                }); 

Directive

app.directive('autoComplete', function($timeout) {     return function(scope, iElement, iAttrs) {             iElement.autocomplete({                 source: scope[iAttrs.uiItems],                 select: function() {                     $timeout(function() {                       iElement.trigger('input');                     }, 0);                 }             });         };     }); 

View

<input auto-complete ui-items="names" ng-init="manualcat='no category entered'" ng-model="manualcat">  

So, how do I piece this all together correctly the Angular way?

like image 855
Gidon Avatar asked Aug 27 '13 08:08

Gidon


People also ask

How do I use angular material autocomplete?

Start by creating the autocomplete panel and the options displayed inside it. Each option should be defined by a mat-option tag. Set each option's value property to whatever you'd like the value of the text input to be when that option is selected.

What is MD autocomplete?

The md-autocomplete, an Angular Directive, is used as a special input control with an inbuilt dropdown to show all possible matches to a custom query. This control acts as a real-time suggestion box as soon as the user types in the input area.


1 Answers

I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.

Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete

So basically you have to return a promise when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $qservice/directive/controller where you issue your HTTP Request.

Example:

function getMyHttpData(){   var deferred = $q.defer();   $http.jsonp(request).success(function(data){     // the promise gets resolved with the data from HTTP     deferred.resolve(data);   });   // return the promise   return deferred.promise; } 

I hope this helps.

like image 101
JustGoscha Avatar answered Oct 18 '22 02:10

JustGoscha