0.常用的注入依赖方法有value, factory, service, provide 以及constant.
1.感觉注入依赖把现有创建的服务作为一个function的参数,那么该function就可以使用已有的服务的内部的函数。
2.将服务作为对象来看,就是可以调用对象的方法。
<html>
<head>
<meta charset="utf-8">
<title>AngularJS 依赖注入</title>
</head>
<body>
<h2>AngularJS 简单应用</h2>
<div ng-app = "mainApp" ng-controller = "CalcController">
<p>输入一个数字: <input type = "number" ng-model = "number" /></p>
<button ng-click = "buttonFunction()">X<sup>2</sup></button> <!--触发函数 sup 上脚标-->
<p>结果: {{result}}<br>x10:{{result_x10}}<br> /2: {{result_d2}} <br> /3: {{result_d3}}</p>
<button ng-click = "talk()">talk</button>
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
/*创建一个名字为'MathService'的自定义服务,
以后我们使用这个服务为参数时,就可以访问它内部的函数。
*/
this.$get = function() {
var temp = {};
temp.multiply = function(a, b) {
return a * b;
}
temp.multiply_x10 = function(a, b) {
return a * b * 10;
}
return temp;
};
});
});
mainApp.factory('MathService1', function() {
var temp = {};
temp.divide = function(a, b) {
return a / b;
}
return temp;
});
mainApp.value("defaultInput", 5);
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
this.square_x10=function(a){
return MathService.multiply_x10(a,a);
}
});
mainApp.service('CalcService1', function(MathService1){
this.divide2 = function(a) {
return MathService1.divide(a, 2);
}
});
mainApp.service('test', function(){
this.talk = function(){
alert("talk is cheap");
}
});
mainApp.controller('CalcController', function($scope, CalcService, CalcService1, defaultInput, MathService1, test) {
/*只要function的参数列表中列出服务test,就可以访问test内部的函数*/
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.result_x10 = CalcService.square_x10($scope.number);
$scope.result_d2 = CalcService1.divide2($scope.number);
$scope.result_d3= MathService1.divide($scope.number, 3);
$scope.buttonFunction = function() {
$scope.result = CalcService.square($scope.number);
$scope.result_x10 = CalcService.square_x10($scope.number);
$scope.result_d2 = CalcService1.divide2($scope.number);
$scope.result_d3= MathService1.divide($scope.number, 3);
}
$scope.talk = function(){
test.talk();
}
});
</script>
</body>
</html>
网页:
[参考: http://www.runoob.com/angularjs/angularjs-dependency-injection.html]