2016-04-28 56 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

是的..只是直接調用該匿名函數內的代碼 –

相關問題