zoukankan      html  css  js  c++  java
  • 【转】简单模拟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()
    

      

  • 相关阅读:
    Android
    nodejs 中 接受前端的数据请求的处理
    nodejs 文件操作
    nodejs 简单的搭建一个服务器
    angular 的跨域处理
    angular 的配置文件的应用
    angular 语法的应用
    淘宝的公共样式
    web编辑器的快捷键
    scss 用法 及 es6 用法讲解
  • 原文地址:https://www.cnblogs.com/oxspirt/p/6026482.html
Copyright © 2011-2022 走看看