Skip to content

Commit cc8994b

Browse files
committed
angularJs 服务
1 parent b455263 commit cc8994b

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

problems.docx

101 Bytes
Binary file not shown.

studys/services.html

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>angularJs 服务</title>
5+
<meta charset="utf-8" />
6+
<script type="text/javascript" src="../libs/basic/angular.min.js"></script>
7+
</head>
8+
<body ng-app="serviceApp">
9+
<div ng-controller="serviceCtrl">
10+
<p>本页面路径: {{localUrl}}</p>
11+
<!-- 延迟赋值 -->
12+
<p>延迟赋值:{{timeoutValue}}</p>
13+
<!-- 秒表 -->
14+
<p>秒表: {{second}}</p>
15+
<!-- 自定义服务的使用 -->
16+
<p>在控制器中使用自定义服务: {{reverseStr}}</p>
17+
<p>在指令中使用自定义服务: <span ng-bind="reverseStr"></span></p>
18+
19+
<!-- $witch服务监控页面变化 -->
20+
<label>
21+
输入: <input type="text" name="changeText" ng-model="changeText" />
22+
</label>
23+
<p>输入变化次数:{{changeCount}}</p>
24+
</div>
25+
<script type="text/javascript">
26+
var app = angular.module('serviceApp', []);
27+
/*angular服务是一个函数或者对象,这些服务可以获取到angular应用声明周期的每一个阶段,和$watch整合,让angular可以监控整个应用,处理事件变化。自定义服务注入时不需要加$*/
28+
app.controller('serviceCtrl', function($scope, $location, $http, $timeout, $interval, reverse) {
29+
/*$location服务, 取页面路径*/
30+
$scope.localUrl = $location.absUrl();
31+
$scope.second = 0;
32+
$scope.changeCount = 0;
33+
$scope.reverseStr = 'how are you, are you ok?';
34+
$scope.reverseStr = reverse.reverse($scope.reverseStr);
35+
/*$http服务 向服务器请求数据*/
36+
/*$http.get('helloWorld.html').then(function(response){
37+
console.log(response);
38+
});*/
39+
40+
/*$timeout服务对应setTimeout函数,设置延迟执行*/
41+
$timeout(function() {
42+
$scope.timeoutValue = '这是一个迟来的值';
43+
}, 2000);
44+
45+
/*$interval服务对应setInterval函数,循环执行一段代码*/
46+
$interval(function() {
47+
$scope.second += 1;
48+
}, 1000);
49+
50+
/*$watch()是一个scope函数,用于监听应用的变化*/
51+
$scope.$watch('changeText', function(newValue, oldValue, rootScope) {
52+
$scope.changeCount += 1;
53+
});
54+
});
55+
56+
/*自定义服务,可以在指令、控制器、过滤器或其他服务中使用*/
57+
app.service('reverse', function() {
58+
/*使用this为服务添加对象和方法*/
59+
this.isReverse = true;
60+
this.reverse = function(text) {
61+
var newArr = text.split('');
62+
return newArr.reverse().join().replace(/,/g, '');
63+
};
64+
});
65+
</script>
66+
</body>
67+
</html>

0 commit comments

Comments
 (0)