Search code examples
angularjsrequirejsangular-amd

How to load a directive into a module after instantiating using requirejs


To describe my hurdle, A little back story. I was injecting all the requirejs path files(directives basically) which contains any directive to my main module in the app.js, which was working perfect. Its somewhat like

define(['angularAMD', 'angular-route', 'angular-resource', 'angularTranslate', 'angularTranslateLoaderStaticFiles', 'bootstrap', 'angular-idle', 'loadingMaskDirective', 'multiselectDirective', 'treeview.directive', 'tabs', 'checklist.directive'], function(angularAMD) { 
var app = angular.module("myApp", ["ngRoute", "ngResource", "ngTable", "myApp.directives", 'ui.bootstrap', 'flow']);
app.config(....){
/**some route provider**/
}...
angularAMD.bootstrap(app);
return app;

I have defined all directives and also injected them to main module. But I want to define some directive in their indivisual controller to reduce initial load. There has to be some method. Right !!

And code in my directive js files looks like..

define(['angular'], function() {
angular.module('myApp').directive('SomeDirective',
        ['$parse', '$compile', '$rootScope', '$filter', function($parse, $compile, $rootScope, $filter) {
.........

So, when I try to define the same in page controller not in app.js, It doesn't work. However I am amazed that the factory function in this case works but not directive.

Any help will be appreciated. Thanks


Solution

  • Have you tried to use app to create the directive?

    define(['app'], function(app) {
    app.directive('SomeDirective',
            ['$parse', '$compile', '$rootScope', '$filter', function($parse, $compile, $rootScope, $filter) {
    .........
    

    An alternative provided by angularAMD is:

    define(['angularAMD'], function(angularAMD) {
    angularAMD.directive('SomeDirective',
            ['$parse', '$compile', '$rootScope', '$filter', function($parse, $compile, $rootScope, $filter) {
    .........
    

    The benefit of 2nd approach is to allow loading of directive before loading of your app.js. See Loading Application Wide Module for more detail.