美文网首页我爱编程
Angular依赖注入详解

Angular依赖注入详解

作者: 小漠穷秋 | 来源:发表于2018-04-06 18:05 被阅读0次

    1.依赖注入
    依赖注入作为控制反转的一种实现。所有的DI实现都需要两个关键环节。
    1.注册机制(向容器中注册服务)
    2.注入并使用(使用的时候如何申明)

    2.angular运行环境体系
    <html>
    <script src='angular.js'></script>
    <script>
    var app = angular.module("myApp",[ui-router]);
    app.directive('aDirective',function(){})//注入指令
    app.controller(firstController,function($scope){})//注入控制器
    app.config();//可以注入provider constant,修改全局模版,提供元provider
    app.run();//可以注入provider factory service value constant 保存全局变量,使用config中的元provider
    app.factory();//注册服务
    app.filter();//注册过滤器
    app.provider('service1',function(){})//注册服务
    </script>
    <div ng-app="myApp" ng-controller="firstController"></div>
    </html>
    因此可以看到,依赖注入可以在任何时候进行。只要注册了服务即可。

    3.注册机制
    通过五个组件进行注册。
    1.value(app.value 在controller回调中使用)
    2.factory(app.factory(a,function(){}) 在service和controller回调中使用)
    3.service(app.service(a,function(){})可以注入factory或者provider中注册的服务)
    4.provider(app.conf($provider){$provider.provide(a,function(){})})app.provider 在config中注入$provider,使用$provider.provider注册
    5.constant(app.constant(a,'1'))

    4.注入并使用
    注入的方式主要有三种:
    1.数组方式:myApp.controller('a',[$a,$b,function(){$a,$b}]));
    2.$inject:myApp.controller(a,function($a,$b){}) controller.inject=['$a','$b'];
    3.隐式:myApp.controller(a,function($a,$b){})

    5.总结
    依赖注入的注册主要通过两种形式。
    1.直接通过全局模块,注册 app.facotry app.service app.value app.constant。这种方式使用简单,但是在config之后加载,并且不能配置。
    2.通过app.provider(A)+config($Aprovider),在config中使用$Aprovider.service 注册并修改服务方式。
    6.源码
    主要通过Function.prototype.toString方法实现。通过apply执行。
    代码见github https://github.com/etoah/Eg/blob/master/Angular/di.html

    相关文章

      网友评论

        本文标题:Angular依赖注入详解

        本文链接:https://www.haomeiwen.com/subject/wtqbmxtx.html