AngularJs's templateUrl : Url or ID?

angularjs, javascript

Solution

I will add to what @QuarK started with, perhaps filling in a bit more detail.

The `$templateCache` is used as a repository for templates once they have been resolved (inline or from a file).

The source of the `script` tag with `text/ng-templates` looks like this:

var scriptDirective = ['$templateCache', function($templateCache) {
  return {
    restrict: 'E',
    terminal: true,
    compile: function(element, attr) {
      if (attr.type == 'text/ng-template') {
        var templateUrl = attr.id,
            // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
            text = element[0].text;

        $templateCache.put(templateUrl, text);
      }
    }
  };
}];

You can see that if a `script` tag is found, and the `attr.type` is `text/ng-template`, then angular puts the content into the `$templateCache` indexed by the `templateUrl`.

Using `script` tags like this has only been introduced recently to Angular. So, this is an option that allows an inline definition without requiring an external file. However, underneath, once resolved, both use the same mechanism to be read and compiled (`$templateCache`).

Hope this helps.

Problem

AngularJS docs provide a `templateUrl` example : using : ``` //ngApp... <div ng-controller="Ctrl"> <div my-customer></div> </div> ``` And in the controller : ``` ....directive('myCustomer', function() { return { templateUrl: 'my-customer.html' }; }) ``` Where my-customer.html is an external file : All ok. but they provide the option to edit it (via jsfiddle) : But there- it is as a template tag ! : ``` <div ng-app="docsTemplateUrlDirective"> <div ng-controller="Ctrl"> <div my-customer></div> </div> <!-- my-customer.html --> <script type="text/ng-template" id="my-customer.html"> Name: {{customer.name}} Address: {{customer.address}} </script> </div> ``` Question : How does NG knows if it's an external file or is it an Tag element ID ? and how can I force it to a certain type ? (p.s. - didn't find it in the docs).

Original source