How to automatically load a module in AngularJS without specifying it as a dependancy

╄→尐↘猪︶ㄣ 提交于 2019-12-08 05:23:28

问题


ngMock does some magic to automatically include itself if you include angular-mocks.js in your index.html.

What's the simplest way to force angular to load a module in test mode simply by including a file and not having to edit any module dependencies.


回答1:


The only way to load a module is by calling angular.module(...). ngMocks loads "itself" by calling:

angular.module('ngMock', ['ng']).provider(...).config(...);

You don't need to declare a module as a dependency to load it. You can just include angular.module('<moduleName>', [<moduleDependencies>...]); in its script.


If you mean "how is ngMock automagically added to the dependency list of any module loaded using window.module or angular.mock.module, it is because ngMocks creates a custom injector, such that it takes the list of dependencies and prepends 'ngMock':

window.inject = angular.mock.inject = function() {
  ...
  return isSpecRunning() ? workFn() : workFn;
  ...
  function workFn() {
    var modules = currentSpec.$modules || [];

    modules.unshift('ngMock');   // <-- this line does the trick
    modules.unshift('ng');
    ...

You could create your own function that prepends your module in the list of dependencies before instantiating, but I hardly believe this will help in testing. On the contrary, it will be one more source of errors (and will result in possibly "hiding" dependency errors).



来源:https://stackoverflow.com/questions/21278514/how-to-automatically-load-a-module-in-angularjs-without-specifying-it-as-a-depen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!