Home >Web Front-end >JS Tutorial >Efficiently utilize the built-in services $http, $location, etc. in Angular_AngularJS
AngularJS provides us with numerous built-in services, through which we can easily implement some common functions. The following is a summary of the commonly used built-in services in Angular.
1.$location service
$location服务用于返回当前页面的URL地址,示例代码如下: var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $location) { $scope.myUrl = $location.absUrl(); });
Here the myUrl variable is defined for the $scope object, and then the $location service is used to read the URL address and store it in myUrl.
2..$http service
$http is the most commonly used service in AngularJS, and it is often used for data transfer from the server. In the example below, the service sends a request to the server, and the application responds with data sent by the server.
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http) { $http.get("welcome.htm").then(function (response) { $scope.myWelcome = response.data; }); });
3.$timeout() service and $interval() service
The functions of these two services correspond to the setTimeout() and setTimeInterval functions in JavaScript. A simple real-time update time example is as follows:
app.controller('myCtrl', function($scope, $interval) { $scope.theTime = new Date().toLocaleTimeString(); $interval(function () { $scope.theTime = new Date().toLocaleTimeString(); }, 1000); });
In addition to the built-in services provided in Angular, we can also define our own services by using service. The following is a basic code framework for defining services:
app.service('hexafy', function() { this.myFunc = function (x) { return x.toString(16); } });
After defining the service, we can use it just like the built-in Angular service:
app.controller('myCtrl', function($scope, hexafy) { $scope.hex = hexafy.myFunc(255); });
The above is a summary of commonly used built-in services in Angular. I hope it will be helpful to everyone's learning.