好好爱自己!

【转】简单模拟angular的依赖注入

原文:http://www.oschina.net/code/snippet_1181081_35136

代码片段

var angular = function(){};
 
Object.defineProperty(angular,"module",{
    value:function(modulename,args){
        var module = function(){
            this.args = args;
            this.factoryObject = {};
            this.controllerObject = {};
        }
        module.prototype.factory = function(name,service){
            //if service is not a function ...  
            //if service() the result is not a object ... and so on
            this.factoryObject[name] = service();
        }
        module.prototype.controller = function(name,args){
            var _self  = this;
            //init
            var content = {
                $scope:{},
                scope:function(){
                    return content.$scope;
                }
            //  $someOther:{...}
            }
 
            var ctrl = args.pop();
            console.log(typeof ctrl);
            var factorys = [];
            while(service = args.shift()){
                if(service in content){
                    factorys.push(content[service])
                }else{
                    factorys.push(_self.factoryObject[service])
                }
                 
            }
            ctrl.apply(null,factorys);
 
            _self.controllerObject[name] = function(){
                return content;
            };
        }
        var m = new module();
        window[modulename] = m;
        return m;
    }
})

  代码测试

var hello = angular.module('Test');
 
hello.factory("actionService",function(){
    var say = function(){
        console.log("hello")
    }
    return {
        "say":say
    }
})
 
hello.controller("doCtrl",['$scope',"actionService",function($scope,actionService){
    $scope.do = function(){
        actionService.say();
    }
}]);

//调用
hello.controllerObject.doCtrl().scope().do()

  

posted @ 2016-11-03 14:30  立志做一个好的程序员  阅读(225)  评论(0编辑  收藏  举报

不断学习创作,与自己快乐相处