zoukankan      html  css  js  c++  java
  • AngularJS DI(依赖注入)实现推测

    AngularJS DI(依赖注入)

    http://www.cnblogs.com/whitewolf/archive/2012/09/11/2680659.html

      回到angularjs:在框架中为我们提供了angular.injector(modules)DI注入注射器。但是在我们使用注入的时候常常是不需要关心具体的如何注入。我们只需要按照其规则书写我们的angularjs代码就会很容易的得到angularjs的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);​
    

    分析

    控制器 myController 是一个函数, 其具有 $scope, $alert 两个参数, 

    这两个参数 第一个是APP应用域, 第二个是依赖的服务, 其实现为 myModule.factory 定义的 $alert 服务。

    myController 控制器,在html 声明时候,被初始化, 即使被调用。如下HTML

    <div ng-app="myModule"  ng-controller="myController" ng-init="msg='test for alert'" >
        <input ng-model="msg">
    <button ng-click="message(msg);">click me</button>
       <br/> {{msg}}
    </div>

    未见任何调用 myController 地方,如何控制入参传入? 且 $alert参数能对应到 myModule.factory 定义的 $alert 服务??

    猜测是框架实现的调用流程,并将 服务注入到 myController 控制器, 当控制器被初始化时。

    具体牵扯到JS函数定义具有自省性质, 使用toString方法,并将参数名解析出来, 然后到 服务列表中找到 参数名对应的服务, 然后调用 myController 方法。

    JS的自省测试如下:

    function test($scope, $alert) {console.log("aaa")}

    test.toString().match(/([^()]*)/)
    ["($scope, $alert)", index: 13, input: "function test($scope, $alert) {console.log("aaa")}", groups: undefined]0: "($scope, $alert)"groups: undefinedindex: 13input: "function test($scope, $alert) {console.log("aaa")}"length: 1__proto__: Array(0)
    test.toString().match(/([^()]*)/)[0] "($scope, $alert)"

     

    参考:

    https://segmentfault.com/q/1010000002581288

  • 相关阅读:
    jQuery学习笔记(一):入门
    jQuery学习笔记(二):this相关问题及选择器
    数据库基础
    有关程序员转行的想法
    在团队中如何带领新手——阅读有感
    C#中的集合类——ArrayList
    .NET基础——ASSCII码表
    C#中的文件操作2
    C#中的文件操作1
    C#中的StringBuilder
  • 原文地址:https://www.cnblogs.com/lightsong/p/9393375.html
Copyright © 2011-2022 走看看