-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefinition.html
More file actions
68 lines (58 loc) · 2.03 KB
/
Copy pathdefinition.html
File metadata and controls
68 lines (58 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义服务</title>
<script src="angular.js"></script>
</head>
<body>
<!--<div ng-app="myApp" ng-controller="myCtrl">-->
<!--<p>255 的16进制是:</p>-->
<!--<h1>{{hex}}</h1>-->
<!--</div>-->
<!--<p>自定义服务,用于转换16进制数:</p>-->
<!--<script>-->
<!--var app = angular.module('myApp', []);-->
<!--//下面是核心:-->
<!--// 1、service()方法,传入一个对象和一个回调函数-->
<!--app.service('hexaf', function() {-->
<!--this.myFunc = function (x) {-->
<!--return x.toString(16);-->
<!--}-->
<!--});-->
<!--app.controller('myCtrl', function($scope, hexaf) {-->
<!--$scope.hex = hexaf.myFunc(255);-->
<!--});-->
<!--</script>-->
<!--自定义服务总结-->
<!--
1、首先利用app 调用service()方法且传入两个参数,一个是要自定义的服务,另一个是回调函数
2、在回调函数里面给this添加一个方法,这个方法即包含服务的功能
3、app再调用控制器方法,传入两个参数,一个是控制器属性值,另一个参数是回调函数,并传入两个参数:一个是作用域$scope,
另一个是自定义服务;
4、自定义服务调用service()中回调函数this的方法,并传入相应参数,将其赋值给$scope的参数
-->
<!--尝试自己自定义一个服务:得出从1开始到某一个值的和-->
<div ng-app="myApp" ng-controller="myCls">
{{total}}
</div>
<script>
var app=angular.module("myApp",[]);
// 开始创建自定义服务
app.service('addNumber',function(){
this.func=function(num){
var init=1;
var totalNum=1;
for(var i=0;i<num-1;i++){
init++;
totalNum=totalNum+init;
}
return totalNum;
}
});
app.controller('myCls',function($scope,addNumber){
$scope.total=addNumber.func(100);
})
</script>
</body>
</html>