How to check for the existence of a module without an error being raised?

前端 未结 7 875
小蘑菇
小蘑菇 2020-12-24 01:04

In Angular 1.2, ngRoute is a separate module so you can use other community routers like ui.router instead.

I\'m writing an open-source mod

7条回答
  •  既然无缘
    2020-12-24 01:44

    The original answer is legit. However, as an alternative, I wrote this when I needed to "find or create" the modules. There's a number of use cases, but generally, it lets you not have to worry about file load order. You could either put this in a initialModules.js... or the top of all your individual service/directive files start with something like this. This little function works like a charm for me:

    var initialModules = [
      {name: 'app.directives', deps: ['ui.mask']},
      {name: 'app.services'},
      {name: 'app.templates'},
      {name: 'app.controllers'}
    ];
    
    initialModules.forEach(function(moduleDefinition) {
      findOrCreateModule(moduleDefinition.name, moduleDefinition.deps);
    });
    
    function findOrCreateModule(moduleName, deps) {
      deps = deps || [];
      try {
        angular.module(moduleName);
      } catch (error) {
        angular.module(moduleName, deps);
      }
    }
    
    
    ///// OR... in like "myDirective.js"
    findOrCreateModule('app.directives').directive('myDirective', myDirectiveFunction);
    

提交回复
热议问题