2
votes

I want to package and ship an angular module that includes a bunch of directives and html templates.

I am trying to bundle all the html templates for my directive into one html file and include that html file using ng-include. The templates are then used by various directives in the module.

So the 3 components are:

A few standard directives

function Directive1($compile, $rootScope) {
    return {
        restrict: "E",
        scope: {
            options: "="
        },
        templateUrl: "directiveTemplate1.html",
        link: function (scope, element, attrs) {}
    }
}

function Directive2($compile, $rootScope) {
    return {
        restrict: "E",
        scope: {
            options: "="
        },
        templateUrl: "directiveTemplate2.html",
        link: function (scope, element, attrs) {}
    }
}

An html file containing my templates at /path/to/template.html

<script type="text/ng-template" id="directiveTemplate1.html">
    <div> Template ONE </div>
</script>


<script type="text/ng-template" id="directiveTemplate2.html">
    <div> Template TWO </div>
</script>

And finally the html page that ties it all together

<html>
    <body>
    <directive1/>

     <directive2/>
    </body>

    <ng-include src="'/path/to/templates.html'">
</html>

Is it possible to do this?

I want to do it like this so I can ship the angular module to a 3rd party and they only need to include a minified js file for the module and a single html file with all the partial views. I can't inline my template html in the directives as the partials are quite large.

I would think that angular would include and parse the templates.html file on page load and insert the templates into the templateCache for use by the directives later - when the directive's templateUrl is resolved asynchronously.

I've tried this and it seems like the directive can't find the templates.

Any ideas?

2

2 Answers

3
votes

Much better options would be to package HTML templates into JS file itself, so your module is shipped with HTML already available templates and nothing will needs to be downloaded.

The idea is that, Angular checks presence of templates (by path) in $templateCache and if template is there (has already been downloaded or was put there manually) then it just returns content of it immediately. You need similar behaviour. By the way, script directive (with type="text/ng-template") does the same - just puts its innerHTML into template cache.

To achieve this you either put templates into $templateCache manually or - more convenient - to automate this task with tools like ngHtml2js, which are available for all main build systems like gulp and grunt.

1
votes

Refer Angular-bootstrap library. they have embedded their template inside JS file itself. http://angular-ui.github.io/bootstrap/ On this link select Create a Build option, select any of the module and download it. Check the source code of .tpl.js file.