Q:

How to hit the url from the service in angularjs? 

var app=angular.module('httpExample',[]);
app.controller("FetchController",["$scope","$http","$templateCache",function($scope,$http,$templateCache){
    var req={
             method : 'GET',
              url : 'http://www.w3schools.com/angular/customers.php',
              cache:'templateCache',
                  headers: {
                       'Content-Type': undefined
                     },
    };
    $scope.fetch = function() {

        $http(req). 
            success(function(response,status,headers,config)
                    {

                        $scope.data=response;
                        console.log(angular.toJson(response));
                    }). 
            error(function(data)
                {
                        console.log("Error : " + data);
                });
            };
}]);

I the above code ,I tried to hit the url from the controller and display it response on the page..Now I am trying to hit the url from the service and display the response on the page ..Is it possible..Can anyone help me out to solve this problem 

A:

This would be your refactored code.  The logic for the request is now encapsulated in the service. 
var app=angular.module('httpExample',[]);
app.controller("FetchController",["$scope","someService","$templateCache", 
  function($scope,someService,$templateCache){

    $scope.fetch = function() {
        someService.hitTheUrl()
            .success(function(response) {
                $scope.data=response;
                console.log(angular.toJson(response));
            })
            .error(function(data) {
                console.log("Error : " + data);
            });
    };
}])

.factory('someService', [$http, function ($http) {
    return {
        hitTheUrl: function () {
            var req = { 
                method : 'GET',
                url : 'http://www.w3schools.com/angular/customers.php',
                cache:'templateCache',
                headers: {
                    'Content-Type': undefined
                },
            };

            return $http(req);
        }
    };
}]);

