angular服务
在 AngularJS 中,服务是一个函数或对象,可在你的 AngularJS 应用中使用。AngularJS 内建了30 多个服务。有个$location 服务,它可以返回当前页面的 URL 地址。$timeout服务,设置经过多长时间执行某个事件。$interval服务,间隔多长时间循环地执行某个事件。
$location,$timeout,$interval服务示例
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Angular Service</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>
<div ng-controller="locationController">
{{location}}
</div>
<hr>
<div ng-controller="httpController">
{{responseData}}
</div>
<hr>
<div ng-controller="timeoutController">
<ul>
<li ng-repeat="message in messages">
{{message}}
</li>
</ul>
</div>
<hr>
<div ng-controller="intervalController">
<ul>
<li ng-repeat="message in messages">
{{message}}
</li>
</ul>
</div>
</body>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("myApp",[]);
app.controller("locationController",function($scope,$location){
$scope.location = $location.absUrl();
});
app.controller("httpController",function($scope,$http){
$http.get("data.txt").then(function(response){
$scope.responseData = response.data;
});
});
app.controller("timeoutController",function($scope,$timeout){
$scope.messages = [];
var i = 0;
$timeout(function() {
$scope.messages.push(++i);
}, 2000);
});
app.controller("intervalController",function($scope,$interval){
$scope.messages = [];
var i = 0;
$interval(function() {
$scope.messages.push(++i);
}, 2000);
});
</script>
</html>
自定义服务
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Customer Service</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>
<div ng-controller="customerSerController">
<input type="text" ng-model="value">
{{value}}
{{binaryValue}}
</div>
</body>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("myApp",[]);
app.service("numberFormat",function(){
this.toBinary = function(x){
return x/2;
};
});
app.controller("customerSerController",function($scope,numberFormat){
$scope.binaryValue = numberFormat.toBinary(55);
});
</script>
</html>
转载请注明原文地址: https://ju.6miu.com/read-7244.html