0

I am using RequireJS in my Angular app. I would like to require my pill where it is actualy used.

pill.js

define([], function() {
    angular.module('app').directive('pill', function() {
        return function(a,b,c) {
            b.html("A pill");
        };
    });
});

incl.html

<div load-script="require(['pill']);"></div>
<div pill>test</div>

main.html

<html ng-app="app">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
        <script src="http://requirejs.org/docs/release/2.1.10/comments/require.js"></script>
    </head>
    <body>
        <script>
            var app = angular.module("app", [])
                app.directive('loadScript', function() {
                        return {
                            link: function(scope, element, attrs) {
                                (new Function(attrs.loadScript))();
                            }
                        };
                    }
                );
        </script>
    <div ng-include="'incl.html'"></div>
    </body>
</html>

This short example should declare a pill directive that just transform text from test to A pill inside incl.html file. However, it doesn't work. I guess it is because the pill directive is registered after incl.html is compiled.

I want avoid declaring directives somwhere globaly for example inside main.html because it is not used there. Is this requirement achievable in elegant way?

svobol13
  • 1,842
  • 3
  • 25
  • 40

1 Answers1

0

The best way to load directive on demand is to create it using $compileProvider which you will need to cache during your app.config phase. Also, instead of using ng-include, I would suggest you load the directive you need when partial view that uses it loads.

To do that, it is actually quite complicated. I created following library that should help get you started:

http://marcoslin.github.io/angularAMD/

angularAMD would make it easier for your create a independent file that allow you to configure RequireJS dependency to load the directive only on the partials that needs it.

marcoseu
  • 3,892
  • 2
  • 16
  • 35