Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate Angular UI Bootstrap Typeahead with newest $resource

According to this Paweł Kozłowski's answer, Typeahead from AngularUI-Bootstrap should work when asynchronously obtaining popup items with $resource in newest Angular versions (I'm using 1.2.X).

Plunk - Paweł's version - Typeahead with $http

I guess I don't know how to use it properly (As a result I get an error in typeaheadHighlight directive's code - typeahead treats instantly returned Resources as strings and tires to highlight them).

Plunk - Typeahead with $resource

I think the critical code is:

$scope.cities = function(prefix) {
    var p = dataProviderService.lookup({q: prefix}).$promise;
    return p.then(function(response){
        $log.info('Got it!');
        return response.data;
    });
    return p;
};

I've tried bunch of stuff - returning $promise (version from Plunker), query(), then().
Currently, I'm using $http for this functionality in my app and I'm ok with it. Still, just wanted to know how to achieve the same with $resource.

You might want to take a look at this: https://github.com/angular/angular.js/commit/05772e15fbecfdc63d4977e2e8839d8b95d6a92d
is ui.bootstrap.typeahead compatible with those changes in $resource's promise API ?

like image 628
vucalur Avatar asked Nov 24 '13 17:11

vucalur


3 Answers

Should be:

$scope.cities = function(prefix) {
    return dataProviderService.lookup({q: prefix}).$promise.then(
      function(response){
        // might want to store them somewhere to process after selection..
        // $scope.cities = response.data;
        return response.data;
    });
};

This is based of the angular commit mentioned above, and it worked for me on Angular 1.2.13

like image 164
Andrew Lank Avatar answered Sep 17 '22 23:09

Andrew Lank


Thanks to the answer from @andrew-lank, I did mine with $resource as well. I didn't have a data attribute in my response though. I used the query method on $resource, which expects a responsetype of array so maybe that is why there is no data attribute. It is an array of Resource objects, each of which contains the data. So my code is slightly simpler, looks more like this:

$scope.cities = function(prefix) {
    return dataProviderService.query({q: prefix}).$promise.then(
      function(response){
        return response;
    });
};
like image 31
Tony Z Avatar answered Sep 17 '22 23:09

Tony Z


I ran into this same problem and it had me banging my head against the wall. The problem is with the data service since it is returning an array of strings instead of wrapping them in a JSON object. $resource will not work with an array of strings.

For additional info, check out this answer: One dimensional array of strings being parsed to 2d by angular resource

like image 37
Private Winger Avatar answered Sep 17 '22 23:09

Private Winger