Skip to main content

Using ngTagsInput with $resource

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· One min read
Stephan Hochdörfer
Head of IT Business Operations

Recently in an AngularJS project we used the ngTagsInput directive for AngularJS. In the documentation it is shown how to set-up your own function to load the data for the autocomplete functionality. Since our API returned the data in a way that ngTagsInput did not expected it, I needed a way to convert or extract the data before returning it to ngTagInput. It turned out to be quite easy:

$scope.loadTags = function (query) {
var deferred = $q.defer();
$resource('/tags/', {q: query}, {}).get().$promise.then( function (response) {
var tags = [];
angular.forEach(response.data, function (item) {
if (item.name) {
tags.push({ text: item.name});
}
});
deferred.resolve(tags);
});

return deferred.promise;
};

I was able to grab the response from the API, iterate over the returned items and create the return value (an array of strings) as expected by ngTagsInput.