angularjs DI簡單模擬

簡單模擬了一下angularjs的DI.html

注入器,簡單思路: 1 Injector容器供用戶注入jquery

                       2 監聽onload事件,找到controller,而後執行對應方法angularjs

var Injector =  (function(){
    
    window.onload = compile;
    function compile(){
        $("[controller]").each(function(ctrl){
            var methodName = $(this).attr("controller");
            var method = window[methodName];
            var methodStr = method.toString();
            var injectionstr = methodStr.substring(methodStr.indexOf("(")+1,methodStr.indexOf(")")).split(",");
            var injectionArr = [];
            for(var i=0;i<injectionstr.length;i++){
                injectionArr.push(Injector.get(injectionstr[i]));
            }
            method.apply(this,injectionArr);
        });

    }
    
    return {
        factory :function(name,instance){
            this[name] = instance();
        },
        get :function(name){
            return this[name];
        }
    }
}())

測試:app

<html>
<head>
<script src="jquery.js"></script>
<script src="injector.js"></script>
<script>
Injector.factory("$timeService",function(){
    return {
        printTime : function(){
            console.log(new Date());
        }
    }
});

function ctrl($timeService){
    $timeService.printTime();
}
</script>
</head>
<body>
<div controller="ctrl">
</div>

</body>
</html>

結果:Mon Sep 09 2013 19:28:16 GMT+0800 (澳大利亞西部標準時間)測試

相關文章
相關標籤/搜索