再谈angularjs DI(Dependency Injection)2013-02-14 51cto 破狼在前面已经介绍了关于angularjs,以及扩展了一些jQuery ui的一些组件为angularjs的directive。在这里应进口007 在上篇留言我们来看看在angularjs中的DI特性。DI:依赖注入,是一种软件设计模式,应DIP依赖倒置原则,描述组件之间高层组件不应该依赖于底层组件。依赖倒置是指实现和接口倒置,采用自顶向下的方式关注所需的底层组件接口,而不是其实现。其应用框架则为IOC,在.net中有很多我们熟悉的IOC框架,如Unity,Castle windsor,Ninject,Autofact等等,其常常分为构造注入,函数注入,属性注。同时在IOC和Service Locator(服务查找),如果你想更多的了解IOC和DI请参见martin fowler的Inversion of Control Containers and the Dependency Injection pattern。回到angularjs:在框架中为我们提供了angular.injector(modules)DI注入注射器。但是在我们使用注入的时候常常是不需要关心具体的如何注入。我们只需要按照其规则书写我们的angularjs代码就会很容易的得到angularjs的DI特性,DI方式有三种:1:推断式注入:在angularjs中我们可以在我们需要注入的地方按照名称注入,这里要求参数名称必须和注入服务实例名称相同,一种名称约定。angularjs会提取参数名称查找相应DI实例注入。例如:
var myModule = angular.module("myModule", []);myModule.factory("$alert", function($window) {return {alert: function(text) {$window.alert(text);}};});var myController = function($scope, $alert) {$scope.message = function(msg) {console.log(msg);$alert.alert(msg);};};myModule.controller("myController", myController);在上面实例我利用已知的window服务新建了一个alert的服务.并利用注入到我们的controller使用.这里采用的都是约定注入(根据参数名称注入).jsfiddle在线演示http://jsfiddle.net/whitewolf/zyA5B/7/2:标记注入:在angularjs中我们可以利用$inject标注DI注入,这里需要注入服务名称的顺序和构造参数名对应.这里可以解决以上约定的死板性.将上例代码改变为如下:代码如下:
var myModule = angular.module("myModule", []);myModule.factory("$alert", ["$window", function($window) {return {alert: function(text) {$window.alert(text);}};}]);var myController = function($scope, $alert) {$scope.message = function(msg) {console.log(msg);$alert.alert(msg);};};myController.$inject = ["$scope", "$alert"];myModule.controller("myController", myController);jsfiddle在线演示http://jsfiddle.net/whitewolf/zyA5B/8/