This article mainly introduces how to efficiently use the built-in services in Angular. What are the built-in services of Angular that you know? Interested partners can refer to AngularJS to provide us with many built-in services, with these built-in services, you can easily implement some common functions. The following is a summary of commonly used built-in services in Angular.
1. $ location service
$ Location is used to return the URL address of the current page. The sample code is as follows: var app = angular. module ('myapp', []); app. controller ('mermersctrl', 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 common service in AngularJS. It is often used for server data transmission. In the following example, the Service sends a request to the server and the application responds to the data transmitted 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. An example of a simple real-time update time 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 by Angular, we can also define services by ourselves. Here is a basic code framework for defining services:
app.service('hexafy', function() { this.myFunc = function (x) { return x.toString(16); } });
After defining a service, we can use it like using 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, hoping to help you learn.