Currently, I want to get data from the API by sending some search parameters using the AngularJS service. In my ng model, I have a variable called search, and I would like to use this variable as a parameter for the API URL.
My first (unsuccessful) approach was to use the $ scope.search variable directly inside the service:
$http.get('http://www.omdbapi.com/?s='+ $scope.search +'&type=series&r=json').then(function(data){
deferred.resolve(data);
});
I read that transferring the $ scope to the service is not possible (and should not be done anyway), so how can I use the scope variable as a parameter in the service, is there also a cleaner way to set the parameters besides adding a line myUrl + search?
full code:
myApp.service('showsService', function($http, $q){
var deferred = $q.defer();
$http.get('http://www.omdbapi.com/?s=sherlock&type=series&r=json').then(function(data){
deferred.resolve(data);
});
this.getShows = function(){
return deferred.promise;
}
});
myApp.controller("showsController", function($scope, showsService){
$scope.$watch('search', function() {
fetch();
});
function fetch(){
var promise = showsService.getShows();
promise.then(function(data){
$scope.showsResult = data.data.Search;
});
}
});