---
title: "深入angular.js依赖注入"
author: "bjtale"
date: "2016-03-18T09:03:43Z"
tags: []
categories: ["Web前端"]
slug: "angular-js"
draft: false
lastmod: "2016-03-18T09:05:13Z"
id: 2284464
url: "https://bjtale.iteye.com/blog/2284464"
---

angular.js是实现了依赖注入的前端框架，通常这个概念出现在spring类似的后端框架中。angular.js对依赖注入的实现思路是：定义和动态地注入依赖对象到另一个对象中，使注入对象中可使用所有依赖注入对象提供的功能。

  有人将这种实现区分为提供者和注入器：

  1）提供者，本质上是angular.js模块的一部分，模块使用注入器注册提供者，提供者实际上是包含了所有注入者提供的必须功能对象的实例。

  2）注入器，作为一种服务负责监控提供者对象的实例。为每一个使用提供者的模块提供一个注入器服务实例，提供者对象收到依赖请求时，注入器服务即返回目标实例。

```
<!DOCTYPE HTML>
<html ng-app='myApp'>
	<head>
		<meta charset='utf-8'>
		<title>3</title>
	</head>

	<body>
		<div ng-controller='CtrlA'>

			<h3>Message from myApp:</h3>
			{{message}}
		</div><hr>

		<div ng-controller='CtrlB'>

			<h3>Message from module:</h3>
			{{message}}
		</div>
		<script src='http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js'></script>
		<script>
			var mod = angular.module('myMod',[]);
			mod.value('msgA','Message from a module');
			mod.controller('CtrlB',['$scope','msgA',function($scope,msg){
				$scope.message = msg;
			}]);

			var myApp = angular.module('myApp',['myMod']);
			myApp.value('msgB','Message from app bases module');
                        //msgA,msgB available here.
			myApp.controller("CtrlA",['$scope','msgB',function($scope,msg){
				$scope.message = msg;
			}])
		</script>
	</body>
</html>
```

  以上示例实现了自定义提供者，首先将myMod模块注入到myApp模块中，并且每一个模块都存在值提供者。这种注入会使myApp模块同时具有CtrlA和CtrlB控制器的功能，因此在该模块中可以同时使用自定义值提供者和另一模块的值提供者。