Search code examples
javascripthtmlangularjsangularjs-routing

ng-template to Variable from src


I want to load the contents of my template into a variable. At the moment my Code looks like this.

HTML

<script type="text/ng-template" id="a.html" src="templates/a.html"></script>

JS

vm.template = $templateCache.get('a.html');
console.log("Template: " + vm.template);

This should Load the contents of 'templates/a.html' into vm.template. Sadly this does not work. The variable vm.template doesn't contain the template.

The variable does not contain the template

What I found out while testing is that if i write the contents of the template directly into the script tags like this

<script type="text/ng-template" id="a.html">Hello!</script>

It actually works.

The variable contains the template


Solution

  • Using src on ng-template may not work:

    You can either use an ng-include:

    <script type="text/ng-template" id="a.html">
        <div ng-include="'templates/a.html'"></div>
    </script>
    

    or do this in your routing config:

    .config(function ($routeProvider) {
        $routeProvider
            .when("/", {
                templateUrl: 'templates/a.html',
                controller: 'aController'
            }).when("/second", {
                templateUrl: 'templates/b.html',
                controller: 'bController'
            }).otherwise({redirectTo: "/"});
    });
    

    Also, these does a /templates/a.html GET request to your server (make sure you have configured your statics)