大家都知道angular 依赖注入很神奇,跟我们平常写代码的风格思维差别很大,不过仔细分析确是一个很有意思的东西,依赖注入早期也叫依赖倒置,是java中有的。废话不多少直接上例子 本帖属于原创,转载请出名出处。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>无标题文档</title>
</head>
<body ng-app="myApp">
<div ng-controller="firstController">
</div>
<script>
var angular = {
injectionName: {
$scope: {
$$ChildScope: null,
$$childHead: null,
$$childTail: null,
$$listenerCount: 'Object',
$$listeners: 'Object',
$$nextSibling: null,
$$prevSibling: null,
$$watchers: null,
$$watchersCount: 0,
$id: 2,
$parent: 'Scope',
},
$injector: {
annotate: function (fn, strictDi, name) {
},
get: function (serviceName, caller) {
},
has: function (name) {
},
instantiate: function (Type, locals, serviceName) {
},
invoke: function (fn, self, locals, serviceName) {
},
modules: 'Object',
strictDi: false,
},
$rootScope: {
$$ChildScope: function(){},
$$applyAsyncQueue: Array[0],
$$asyncQueue: Array[0],
$$childHead: 'ChildScope',
$$childTail: 'ChildScope',
$$destroyed: false,
$$isolateBindings: null,
$$listenerCount: 'Object',
$$listeners: 'Object',
$$nextSibling: null,
$$phase: null,
$$postDigestQueue: Array[0],
$$prevSibling: null,
$$watchers: null,
$$watchersCount: 0,
$id: 1,
$parent: null,
$root: 'Scope'
},
$http: function(requestConfig) { if (!isObject(requestConfig)) {
throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
} if (!isString($sce.valueOf(requestConfig.url))) {
throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
} var config = extend({
method: 'get',
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse,
paramSerializer: defaults.paramSerializer,
jsonpCallbackParam: defaults.jsonpCallbackParam
}, requestConfig); config.headers = mergeHeaders(requestConfig);
config.method = uppercase(config.method);
config.paramSerializer = isString(config.paramSerializer) ?
$injector.get(config.paramSerializer) : config.paramSerializer; $browser.$$incOutstandingRequestCount(); var requestInterceptors = [];
var responseInterceptors = [];
var promise = $q.resolve(config); // apply interceptors
forEach(reversedInterceptors, function(interceptor) {
if (interceptor.request || interceptor.requestError) {
requestInterceptors.unshift(interceptor.request, interceptor.requestError);
}
if (interceptor.response || interceptor.responseError) {
responseInterceptors.push(interceptor.response, interceptor.responseError);
}
}); promise = chainInterceptors(promise, requestInterceptors);
promise = promise.then(serverRequest);
promise = chainInterceptors(promise, responseInterceptors);
promise = promise.finally(completeOutstandingRequest); return promise; function chainInterceptors(promise, interceptors) {
for (var i = 0, ii = interceptors.length; i < ii;) {
var thenFn = interceptors[i++];
var rejectFn = interceptors[i++]; promise = promise.then(thenFn, rejectFn);
} interceptors.length = 0; return promise;
} function completeOutstandingRequest() {
$browser.$$completeOutstandingRequest(noop);
} function executeHeaderFns(headers, config) {
var headerContent, processedHeaders = {}; forEach(headers, function(headerFn, header) {
if (isFunction(headerFn)) {
headerContent = headerFn(config);
if (headerContent != null) {
processedHeaders[header] = headerContent;
}
} else {
processedHeaders[header] = headerFn;
}
}); return processedHeaders;
} function mergeHeaders(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName; defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); // using for-in instead of forEach to avoid unnecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName); for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
} reqHeaders[defHeaderName] = defHeaders[defHeaderName];
} // execute if header value is a function for merged headers
return executeHeaderFns(reqHeaders, shallowCopy(config));
} function serverRequest(config) {
var headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); // strip content-type if data is undefined
if (isUndefined(reqData)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
} if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
config.withCredentials = defaults.withCredentials;
} // send request
return sendReq(config, reqData).then(transformResponse, transformResponse);
} function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response);
resp.data = transformData(response.data, response.headers, response.status,
config.transformResponse);
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
},
$q:function(resolver) {
if (!isFunction(resolver)) {
throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
} var promise = new Promise(); function resolveFn(value) {
resolvePromise(promise, value);
} function rejectFn(reason) {
rejectPromise(promise, reason);
} resolver(resolveFn, rejectFn); return promise;
},
$log: console.log,
$window: window,
$timeout: setTimeout,
$interval: setInterval,
$location: window.location
},
getEle: function (ele, ele2) {
if (arguments.length == 1) {
return document.getElementsByTagName(ele);
} else {
return ele.getElementsByTagName(ele2);
} },
module: function (module_str) {
var ele_arr = this.getEle("*"),
flag = false;
app_ele = null;
for (var i = 0; i < ele_arr.length; i++) {
if (ele_arr[i].getAttribute('ng-app') != null) {
flag = true;
app_ele = ele_arr[i];
break;
} } if (app_ele.getAttribute('ng-app') != module_str) {
throw new Error("angular ng-app " + module_str + " not registered ");
}
if (!flag) {
throw new Error("angular ng-app not registered ");
}
this.tool.appEle = app_ele;
return this.tool; },
tool: {
controller: function (controller_str, functionName) {
var ele_arr = angular.getEle(this.appEle, "*"),
flag = false;
app_ele = null;
for (var i = 0; i < ele_arr.length; i++) {
if (ele_arr[i].getAttribute('ng-controller') != null) {
flag = true;
app_ele = ele_arr[i];
break;
} } if (app_ele.getAttribute('ng-controller') != controller_str) {
throw new Error("angular ng-controller " + controller_str + " not registered ");
}
if (!flag) {
throw new Error("angular ng-controller not registered ");
} var pattern = new RegExp("\\((.| )+?\\)", "igm");
var str = functionName.toString().match(pattern)
str = str[0].replace(/\s/g, "");
str = str.substring(1, str.toString().length - 1);
var arr = str.split(',');
var args = [];
for (var i = 0; i < arr.length; i++) {
args[i] = angular.injectionName[arr[i]]
}
functionName.apply(null, args); } }
}
angular.module('myApp')
.controller('firstController', function ($scope,$injector) { console.log($scope);
console.log($injector)
}); </script>
</body>
</html>
 

用原生js简单模仿angular的依赖注入的更多相关文章

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

    原文:http://www.oschina.net/code/snippet_1181081_35136 代码片段 var angular = function(){}; Object.defineP ...

  2. angular 实现依赖注入

    1:首先获取module对象var myAppModule = angular.module('myApp', []); 2:定义对象(类似spring中xml声明bean对象<bean id= ...

  3. 原生JS简单的无缝自动轮播

    最近在不断的加强巩固js.在学习jq和vue之后发现很多东西其实都是不明所以,有些底层的东西自己不懂,到头来也只是一昧的使用,一直在用别人的东西,对自己的成长帮助也不大. 万丈高楼平地起,基础打扎实了 ...

  4. 原生js简单调用百度翻译API实现的翻译工具

    先来个在线demo: js翻译工具 或者百度搜索js简单调用百度翻译API工具(不过有个小小的界面显示bug,我想细心的人应该会发现) 或者直接前往该网址:js翻译工具 或者前往我的github:gi ...

  5. 原生js简单实现拖拽效果

    实现弹窗拖拽效果的原理是:按下鼠标并移动——拖拽移动物体,抬起鼠标——停止移动.主要触发三个事件:onmousedown.onmousemove以及onmouseup: 首先搭建结构:一个宽350px ...

  6. Angular的依赖注入(依赖反转)原理说明

    依赖注入(依赖反转)意思是由函数决定要引入什么样的依赖: let mod = angular.module('test',[]); mod.controller('test_c',function($ ...

  7. angular关于依赖注入

    <html> <head> <title>Angular JS Forms</title> </head> <body> < ...

  8. Angular 4 依赖注入

    一.依赖注入 1. 创建工程 ng new myangular 2. 创建组件 ng g componet product1 3. 创建服务 ng g service shared/product 如 ...

  9. 手把手原生js简单轮播图

    在团队带人,突然被人问到轮播图如何实现,进入前端领域有一年多了,但很久没自己写过,一直是用大牛写的插件,今天就写个简单的适合入门者学习的小教程.当然,轮播图的实现原理与设计模式有很多种,我这里讲的是用 ...

随机推荐

  1. 【druid 】数据库连接池

    一.数据库连接池架构 二.数据库连接池的过滤器 spi的思想,加载配置文件的Filter druid.filters.default=com.alibaba.druid.filter.stat.Sta ...

  2. js入门关于函数

    一,函数·关键字(function)复习var·js关键字.用于声明变量.生命在内存模块完成,定义(=)在执行模块完成.var(可以在内存模块提前完成,所以有变量提升的功能.function也是js的 ...

  3. Golang之接口

  4. GanttProject 如何显示今天和项目结束

    GanttProject 如何显示今天和项目结束 GanttProject 在甘特图中可以很直观的看出项目开始和结束. 同时也可以看到今天的. 把今天的时间线打开,默认是关闭.

  5. 程序员装X指南

      一.准备工作“工欲善其事必先利其器.” 1.电脑不一定要配置高,但是双屏是必须的,越大越好,能一个横屏一个竖屏更好.一个用来查资料,一个用来写代码 .总之要显得信息量很大,效率很高. 2.椅子不一 ...

  6. JetBrains GoLand 注册码

    选择license server 输入 http://idea.youbbs.org 完成 要求联网

  7. v4l2框架分析

    参考:https://www.cnblogs.com/fengong/p/4424823.html    http://www.cnblogs.com/fengong/p/4424895.html 一 ...

  8. [ZZ] [精彩盘点] TesterHome 社区 2018年 度精华帖

    原文地址: https://testerhome.com/topics/17646 相逢即是缘分,总有一篇适合您! 感觉好的请点赞收藏 ,感觉分类不严谨的,欢迎反馈给我! 测试方法&测试管理 ...

  9. monodepth 训练记录

    2019年2月22日13:52:37 https://zhuanlan.zhihu.com/p/29968267 这里有个tensorlfow代码的阅读博客: https://zhuanlan.zhi ...

  10. 64 位 Windows 平台开发注意要点之注册表重定向

    Window 系统错误代码 ERROR_SUCCESS,本博客中一律使用 NO_ERROR 代替.虽然 ERROR_SUCCESS 与 NO_ERROR 是完全等价的,都代表成功,但是后者却和其他错误 ...