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

时间:2022-12-14 17:16:47

原文: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()