2016-04-28 77 views
1

我目前正在尝试引用像下面这样的各种指令和服务中的单个AngularJS模块。

module.js

(function() { 
    'use strict'; 

    angular.module('operations.setup.holidays.calendar', []); 

})(); 

当我尝试引用它在一个指令/服务/控制器,它工作正常,但是当我尝试引用它在说一个指令和服务,我得到: Uncaught Error: [$injector:nomod] Module 'operations.setup.holidays.calendar' is not available!

directive.js(工作,如果这是引用'operations.setup.holidays.calendar'唯一)

(function() { 
    'use strict'; 

    angular 
     .module('operations.setup.holidays.calendar') 
     .directive('yearlyCalendarDirective', yearlyCalendarDirective); 

    function yearlyCalendarDirective(){ 
     return{ 
      template: "<h1>Year Calendar Directive</h1>" 
     }; 
    } 
})(); 

service.js(添加类似这将导致指定的错误)

(function(){ 
    'use strict'; 

    angular 
     .module('operations.setup.holiday.calendar') 
     .service('Calendar',Calendar); 

    function Calendar(){ 

    } 
})(); 

Adding something like .module('operations.setup.holiday.calendar',[]) gets rid of the error, but from what I understand this creates a new module instead of referencing the old one?

编辑: 这里是一个JSFiddle

+0

有你在你的其他文件之前加载module.js? – devqon

+0

@devqon是的,我认为这可能是问题,但module.js是第一个加载。 –

回答

1

this answer,呼吁匿名函数并不保证函数将被调用顺序。

也许你可以加载所有的代码在一个匿名函数:

(function() { 
    'use strict'; 
    angular.module('CalendarApp', []); 

    angular.module('CalendarApp').directive('yearlyCalendar', function() { 
    return { 
     restrict: 'E', 
     scope: {}, 
     template: '<span>Here is a YEARLY calendar</span>' 
    } 
    }); 

    angular.module('CalendarApp').directive('monthlyCalendar', function() { 
    return { 
     restrict: 'E', 
     scope: {}, 
     template: '<span>Here is a MONTHLY calendar</span>' 
    } 
    }); 

    angular.module('CalendarApp').service('CalendarData', function() { 
    function CalendarData() { 
     vm = this; 
     vm.today = new Date(); 
     return new CalendarData(); 
    } 
    }); 
})(); 

,如果你有这样的代码在许多文件分离,不使用匿名函数(直接调用的代码,而不是)

+0

谢谢@Diego!这似乎工作!所以如果我想让他们分开,我只是删除匿名函数关闭? '(function(){})();' –

+0

是的..只是直接调用该匿名函数内的代码 –

相关问题