AngularJS 服务(Service)
在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。
有个 $location 服务,它可以返回当前页面的 URL 地址。
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
$http 服务
$http 是 AngularJS 应用中最常用的服务。 服务向服务器发送请求,应用响应服务器传送过来的数据。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
创建自定义服务
你可以创建访问自定义服务,链接到你的模块中:
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
调用方式
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});