Home > Web Front-end > JS Tutorial > Efficiently utilize the built-in services $http, $location, etc. in Angular_AngularJS

Efficiently utilize the built-in services $http, $location, etc. in Angular_AngularJS

WBOY
Release: 2016-05-16 15:09:49
Original
2249 people have browsed it

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(); 
}); 
Copy after login

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; 
 }); 
}); 
Copy after login

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); 
}); 
Copy after login

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); 
 } 
}); 
Copy after login

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); 
}); 
Copy after login

The above is a summary of commonly used built-in services in Angular. I hope it will be helpful to everyone's learning.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template