YouTip LogoYouTip

Angularjs Services

# AngularJS Services In AngularJS, you can create your own services or use built-in services. * * * ## What is a Service? In AngularJS, a service is a function or object that is available for use within your AngularJS application. AngularJS has over 30 built-in services. There is a **$location** service that returns the URL address of the current page. ### Example var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $location) { $scope.myUrl = $location.absUrl(); }); [Try it Β»](#) Note that the **$location** service is passed into the controller as a parameter. To use it, you need to define it within the controller. * * * ## Why Use Services? Among many services, such as the $location service, it can use objects that exist in the DOM, similar to the window.location object, but the window.location object has certain limitations in AngularJS applications. AngularJS constantly monitors the application and handles event changes. Using the **$location** service in AngularJS is better than using the **window.location** object. ### $location vs window.location | | window.location | $location.service | | --- | --- | --- | | Purpose | Allows read/write access to the current browser location | Allows read/write access to the current browser location | | API | Exposes an object that can be read/written | Exposes jQuery-style getters/setters | | Integrated with AngularJS application lifecycle | No | Can access every stage within the application lifecycle, and integrates with $watch | | Seamless integration with HTML5 API | No | Yes (graceful degradation for older browsers) | | Context aware with the application | No, window.location.path returns "/docroot/actual/path" | Yes, $location.path() returns "/actual/path" | * * * ## $http Service **$http** is the most commonly used service in AngularJS applications. The service sends requests to the server, and the application responds to the data sent back by the server. ### Example Use the **$http** service to request data from the server: var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http) { $http.get("welcome.htm").then(function (response) { $scope.myWelcome = response.data; }); }); [Try it Β»](#) The above is a very simple **$http** service example. For more **$http** service applications, please refer to the (#). * * * ## $timeout Service The Angular
← C ConstantsC Variables β†’