AngularJS 服务(Service) AngularJS 内建了30 多个服务
10.6.1. $location 服务, 它可以返回当前页面的 URL 地址。
app.controller('customersCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
10.6.2. $http 服务, 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。 服务向服务器发送请求,应用响应服务器传送过来的数据。
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
10.6.3. $timeout 服务, AngularJS $timeout 服务对应了 JS window.setTimeout 函数。
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
10.6.4. $interval 服务 AngularJS $interval 服务对应了 JS window.setInterval 函数。
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
10.6.5. 创建自定义服务 你可以创建访问自定义服务,链接到你的模块中:
创建名为hexafy 的访问:
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
使用自定义的的服务 hexafy 将一个数字转换为16进制数:
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});