I have been working on implementing search suggestion functionality using a Suggestions API "". The implementation works fine with Ajax GET requests, but when I try to use it with Angular's $http service, I encounter an error in the console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote
resource at https://SuggestionsAPI.net/suggest?key=xyz. This can be fixed by moving the
resource to the same domain or enabling CORS.
After that, I attempted to address this issue as follows:
$httpProvider.defaults.headers.get = { 'Access-Control-Allow-Origin': '*' };
$httpProvider.defaults.headers.get = { 'Access-Control-Request-Headers': 'X-Requested-With, accept, content-type' };
$httpProvider.defaults.headers.get = { 'Access-Control-Allow-Methods': 'GET, POST' };
$httpProvider.defaults.headers.get = { 'dataType': 'jsonp' };
I am currently puzzled why the same GET request is being blocked by the browser when using Angular JS. Any suggestions on how to resolve this would be greatly appreciated.
EDIT: My plan is to assign the suggestions within a function:
app.directive('autoComplete', ['AutoCompleteService', function (AutoCompleteService) {
return {
restrict: 'A',
link: function (scope, elem, attr, ctrl) {
elem.autocomplete({
source: function (searchTerm, response) {
AutoCompleteService.search(searchTerm.term).then(function (autocompleteResults) {
response($.map(autocompleteResults, function (autocompleteResult) {
return {
label: autocompleteResult.JumboID,
value: autocompleteResult.JumboID
}
}))
});
},
minLength: 3,
select: function (event, selectedItem) {
// Do something with the selected item, e.g.
scope.yourObject = selectedItem.item.value;
scope.$apply();
event.preventDefault();
}
});
}
};
})]);