了解angularJS的逐步手动引导
我正在经历关于如何手动引导的angularJS的基础知识.我遇到不同的方法,发现
this approach是最适合的.
angular.element(document).ready(function(){ angular.bootstrap(document,['myapp']) }) 进一步,我遇到了this another way which breaks it to basics.我已经按照我的理解对代码进行了评论,但有人可以向我详细介绍一下事情如何工作. window.onload = function (){ var $rootElement = angular.element(window.document); var modules = [ 'ng',// angular module 'myApp',// custom module // what are we trying to achieve here? function($provide){ $provide.value('$rootElement',$rootElement) } ]; var $injector = angular.injector(modules); // one injector per application var $compile = $injector.get('$compile'); // Compile Service: it traverses the DOM and look for directives and compile and return linking function. No accecess to scope var compositeLinkFn = $compile($rootElement); // collection of all linking function. Here scope is getting accessed var $rootScope = $injector.get('$rootScope'); // Hold of the rootscope compositeLinkFn($rootScope); $rootScope.$apply(); } 此外,请通过提出更多的方法和改进,随时向我介绍这个主题.
这是相同的旧依赖注入,我们在angularjs中随处可见. 最后我们把它传递给angular.injector() var $injector = angular.injector(modules) 还不信?这是更简单的版本(我们在控制器中使用DI的方式) var $injector = angular.injector(['ng','myApp',function($provide){ $provide.value('$rootElement',$rootElement) }]) 现在有两个问题, >为什么我们使用angular.injector? 因为,angular.injector创建一个可用于检索服务以及依赖注入的注射器对象.我们需要这个获取$compile服务和一个范围的实例来绑定该模板. 让角度知道应用程序的根元素.注意到在angular.bootstrap中使用文档(document,[‘myapp’])?这是因为同样的原因 根据official documentation of $rootElement,
既然我们既不使用ng-app也不使用标准的angular.bootstrap方法,因此我们必须手动设置. 接下来,我们尝试从上述步骤中接收到的注入器实例获取$编译服务. var $compile = $injector.get('$compile'); $compile服务是用于编译的服务.调用针对标记的$compile将产生一个可以用于将标记绑定到特定范围的函数(Angular称为链接函数) 再次得到范围,我们使用$inject.get(‘$rootScope’)并将其传递给从$compile获得的复合链接函数. angular.bootstrap(document,[myApp])只是上述步骤中的语法糖.它创建一个注射器实例,在其帮助下设置相关服务,创建应用程序范围并最终编译模板. 从official documentation for angular.bootstrap可以看出,这清楚地表明它返回了一个注射器实例.
相同的故事在official bootstrap guide中显示
最后,不用说,所有这一切都必须在HTML-Document被加载并且DOM准备就绪之后完成. 编辑 这是这个过程的图解表示. 希望它有帮助:) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |