In AngularJS, you can create your own service or utilize one of the many built-in services available.
In AngularJS, a service is a function or object that is accessible and specific to your AngularJS application.
AngularJS provides around 30 built-in services, one of which is the $location
service.
The $location
service offers methods that return information about the current web page’s location.
Utilize the $location service within a controller.
var app = angular.module(‘myApp’, []); app.controller(‘customersCtrl’, function($scope, $location) { $scope.myUrl = $location.absUrl(); }); |
Keep in mind that the $location
service is included as an argument in the controller. To use the service within the controller, it must be declared as a dependency.
For many services, such as the $location service, you could use existing objects from the DOM, like the window.location object; however, doing so may impose some limitations on your AngularJS application.
AngularJS continuously monitors your application, and to manage changes and events effectively, it is recommended to use the $location service instead of the window.location object.
The $http service is one of the most widely used services in AngularJS applications. It sends requests to the server and allows your application to process the response.
Utilize the $http service to fetch 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; }); }); |
The $timeout service in AngularJS is a version of the window.setTimeout function.
Show a new message after a two-second delay.
var app = angular.module(‘myApp’, []); app.controller(‘myCtrl’, function($scope, $timeout) { $scope.myHeader = “Hello World!”; $timeout(function () { $scope.myHeader = “How are you today?”; }, 2000); }); |