博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AngularJS API之$injector ---- 依赖注入
阅读量:4710 次
发布时间:2019-06-10

本文共 1319 字,大约阅读时间需要 4 分钟。

在AngularJS中也有依赖注入的概念,像spring中的依赖注入,但是又有所不同。Spring中使用构造注入或者设值注入的方式,还需要做一些额外的操作,但是angular中只需要在需要的地方声明一下即可,类似模块的引用,因此十分方便。

参考:[angular api doc] ()

推断式注入

这种注入方式,需要在保证参数名称与服务名称相同。如果代码要经过压缩等操作,就会导致注入失败。

app.controller("myCtrl1", function($scope,hello1,hello2){        $scope.hello = function(){            hello1.hello();            hello2.hello();        }    });

标记式注入

这种注入方式,需要设置一个依赖数组,数组内是依赖的服务名字,在函数参数中,可以随意设置参数名称,但是必须保证顺序的一致性。

var myCtrl2 = function($scope,hello1,hello2){        $scope.hello = function(){            hello1.hello();            hello2.hello();        }    }    myCtrl2.$injector = ['hello1','hello2'];    app.controller("myCtrl2", myCtrl2);

内联式注入

这种注入方式直接传入两个参数,一个是名字,另一个是一个数组。这个数组的最后一个参数是真正的方法体,其他的都是依赖的目标,但是要保证与方法体的参数顺序一致(与标记注入一样)。

app.controller("myCtrl3",['$scope','hello1','hello2',function($scope,hello1,hello2){        $scope.hello = function(){            hello1.hello();            hello2.hello();        }    }]);

$injector常用的方法

在angular中,可以通过angular.injector()获得注入器。

var $injector = angular.injector();

通过$injector.get('serviceName')获得依赖的服务名字

$injector.get('$scope')

通过$injector.annotate('xxx')获得xxx的所有依赖项

$injector.annotate(xxx)

样例代码

    

转载于:https://www.cnblogs.com/xing901022/p/4941166.html

你可能感兴趣的文章
切换用户,显示用户名, 调用Windows系统命令
查看>>
修改dede标题长度限制 改此参数后…
查看>>
ubuntu下安装Docker
查看>>
mysql的字符编码
查看>>
《编程之美》读书笔记 -- 1.4买书问题
查看>>
稳定排序
查看>>
libev & libevent简介
查看>>
ProtoBuffer优势
查看>>
@Repository、@Service、@Controller 和 @Component
查看>>
bootstrap-wysihtml5设置值
查看>>
Windows常用快捷键与常用命令
查看>>
290. Word Pattern 单词匹配模式
查看>>
project1
查看>>
const char*, char const*, char*const的区别
查看>>
vue踩坑记-在项目中安装依赖模块npm install报错
查看>>
mySQL优化, my.ini 配置说明
查看>>
mysql系统数据库
查看>>
alwayson监控
查看>>
浅谈 js 函数调用
查看>>
进程与线程
查看>>