-
Notifications
You must be signed in to change notification settings - Fork 0
/
DependencyInjection.html
63 lines (52 loc) · 1.78 KB
/
DependencyInjection.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
<link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h2>AngularJS 简单应用</h2>
<div ng-app = "mainApp" ng-controller = "CalcController">
<p>输入一个数字: <input type = "number" ng-model = "number" class="form-control" style="display: inline-block; width: 80%"/></p>
<button ng-click = "square()" class="btn btn-primary m-3" style="width: 85px; height: 35px">X<sup>2</sup></button>
<p class="m-3">结果: {{result}}</p>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.value("defaultInput", 5); //用于向控制器传递值
/*
factory 是一个函数用于返回值。在 service 和 controller 需要时创建。
通常我们使用 factory 函数来计算或返回值。
*/
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
};
return factory;
});
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</body>
</html>
<!--
AngularJS 提供很好的依赖注入机制。以下5个核心组件用来作为依赖注入:
1. value
2. factory
3. service
4. provider
5. constant
-->