TheWebGuy
TheWebGuy

Reputation: 12555

Typeahead search function

So I am using the typeahead directive that's part of Angular UI project. I have a function that calls a factory (using $resource to call an api). The first function didn't work but the second one did. What's happening differently here? I assumed these would produce the exact same result but apparently I am wrong:

    // this didn't work, it doesn't display a list of items in typeahead, no errors.
$scope.getLocation = function(val) {
    return LocationService.search({ term: val }, function (res) {
        return res.data.map(function (item) {
            return item;
        });
    });
};

// this worked
$scope.getLocation = function(val) {
    return LocationService.search({ term: val }).$promise.then(function (res){
        return res.data.map(function (item) {
            return item;
        });
    });
};

Upvotes: 1

Views: 46

Answers (1)

Mitch Lillie
Mitch Lillie

Reputation: 2407

Do you have $resource wrapped in LocationService? Something like:

function LocationService($resource) {
return {
    search : function(query){
        var locationResource = $resource('url/',
            {},
            {
                search : {
                    method: 'POST',
                    responseType : 'json'
                }
            });
        return locationResource.search({ q : query });
    }
};
}

If so, in your first example, you're just passing a callback as second variable to LocationService, which isn't handled in the function definition. The returned function of $resource can take a callback as a second parameter, but not if you've wrapped it. If you wanted, you could pass the callback to the service itself, like:

function LocationService($resource) {
return {
    search : function(query, cb){
        var locationResource = $resource('url/',
            {},
            {
                search : {
                    method: 'POST',
                    responseType : 'json'
                }
            });
        return locationResource.search({ q : query }, cb);
    }
};
}

Upvotes: 1

Related Questions