AngularJS内建服务以及自定义服务的用法

在AngularJS中, 服务是一个比较重要的部分,它是一个对象或者是函数,可以在你的AngularJS的应用中使用。接下来介绍几种比较常用的内建服务以及自定义服务的方法。

[内建服务]

(1)location服务

location服务返回当前页面的地址,需要注意的是location服务是作为一个参数传递到 controller 中。如果要使用它,需要在 controller 中定义。

>>>代码部分

<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p> 当前页面的url:</p>
<h3>{{myUrl}}</h3>
</div>
<p>该实例使用了内建的 $location 服务获取当前页面的 URL。</p>
</body>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
</script>
</html>

(2)$http服务

$http服务: 服务向服务器发送请求,应用响应服务器传送过来的数据。

>>>代码部分

 <div ng-app="myApp" ng-controller="myCtrl">
<p>欢迎信息:</p>
<h1>{{myWelcome}}</h1>
</div>
<p> $http 服务向服务器请求信息,返回的值放入变量 "myWelcome" 中。</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script>

(3) $timeout服务

AngularJS $timeout 与 JS window.settimeout 函数相对应,实现效果相同

代码如下>>>

 var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});

代码所执行的效果是,2s后执行代码。

(4)$interval服务

AngularJS $interval 与 JS window.settimeinterval 函数相对应,实现效果相同

 var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});

【自定义服务】

1、service

 angular.module("app",[])
.controller("ctrl",function($scope,$hexafy){})
.service('$hexafy', function() {
this.$$gongneng = "将转入的数字,转为16进制";
this.myFunc = function (x) {
return x.toString(16);
}
})

2、factory

factory 是一个函数用于返回值,通常我们使用 factory 函数来计算或返回值。(factory使用上,与service差距不大)

 angular.module("app",[])
.config()
.controller("ctrl",function($scope,hexafy){
$scope.gongneng = hexafy.gongneng;
$scope.num = hexafy.myFunc(255);
})
.factory('hexafy',function(){
var obj = {
gongneng : "将转入的数字,转为16进制",
myFunc:function(x){
return x.toString(16);
}
};
return obj;
})

3、provider

1、在AngularJS中,Service,factory都是基于provider实现的。
2、在provider中,通过$get()方法提供了factory的写法,用于返回 value/service/factory。;
3、provider是三种自定义服务中,唯一可以写进config配置阶段的一种。
如果服务,必须要在配置阶段执行,那么必须使用provider。否则,一般使用Service或factory

 .controller("ctrl",function($scope,hexafy){
$scope.gongneng = hexafy.gongneng;
$scope.num = hexafy.myFunc(255);
}) /*定义一个provider服务*/
.provider('hexafy',function(){
//默认使用Service的写法
// this.gongneng = "将转入的数字,转为16进制";
this.$get = function(){
var obj = {
gongneng : "将转入的数字,转为16进制",
myFunc : function(x){
return x.toString(16);
}
}
return obj;
}
})
上一篇:VLAN配置及Trunk接口配置


下一篇:VLAN实验(2)Trunk接口