Search code examples
angularjsangularjs-http

How to configure Angular.js to user default host?


For example, I have this call:

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
  // this callback will be called asynchronously
  // when the response is available
}).
error(function(data, status, headers, config) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
});

I need it to request http://my-api-url.com/someUrl, but I don't want to type it everywhere because it will change in the future.

How can I configure it globally ?


Solution

  • Use a constant:

    var myApp = angular.module('myApp',[]);
    
    myApp.constant('myUrls', {
        someUrl: 'http://my-api-url.com/someUrl,',
    });
    
    mayApp.directive('myDirective', ['myUrls', function (myUrls) {
        return {
            ....
            // use myUrls.someUrl
            ....
        };
    }]);
    

    AngularJS Module