AngularJS - 如何在DI系统知道的参数的名字呢? [英] AngularJS - How does the DI system know of the name of the arguments?

查看:104
本文介绍了AngularJS - 如何在DI系统知道的参数的名字呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为例直接从官方网站:

function PhoneListCtrl ($scope, $http) {
    $http.get('phones/phones.json').success(function(data) {
        $scope.phones = data;
    });

    $scope.orderProp = 'age';
}

$范围 $ HTTP 参数是对DI系统内部定位相应AngularJS服务的唯一标识符。那么,如何去离子系统中检索这些参数的变量名称,到底是什么?

The $scope and $http arguments are unique identifiers for locating corresponding AngularJS services inside the DI system. So how does the DI system retrieve the variable name of these arguments, exactly?

推荐答案

这是方式的下调版本

var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;

function annotate(fn){
    var $inject
    if (!($inject = fn.$inject)) {
        $inject = [];
        fnText = fn.toString().replace(STRIP_COMMENTS, '');
        argDecl = fnText.match(FN_ARGS);
        angular.forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
            arg.replace(FN_ARG, function(all, underscore, name){
                $inject.push(name);
            });
        });
        fn.$inject = $inject;
    }

    return fn.$inject;
}

演示:小提琴(见控制台);

步骤:

1.调用的toString 在函数返回函数源

2.使用正则表达式
3.使用正则表达式提取从源头参数

Steps:
1. Calling toString in the function returns the function source
2. Remove all comments using regex
3. Extract the arguments from the source using regex

这篇关于AngularJS - 如何在DI系统知道的参数的名字呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆