AngularJS - Templates and $templateCache

In my previous article I described AngularJs scopes. You can read it from the following link

While creating our custom directives, at a certain point, our template code inside the directive may grow complex. To keep it all organized, templates can be linked to the directives differently. For this, we have some alternatives:

Creating another file, of course and linking it to our directives.

For this, all we need to do is yank our template code and paste it inside another HTML, file say "template.html".

Linking this file to our directive can be done this way:

  1. app.directive('myDir'function() 
  2.    return 
  3.    { 
  4.       templateUrl: '~path-to-file/template.html'}; 
  5. });  
Another way to organize our template code outside the directive is to place the template code in our index.html only, within "script" tags. We'll see how.
  1. <div ng-app='myApp'>   
  2.    <script type=”text/ng-template” id=”template.html”> <! – template code here --> </script>   
  3.    <input my-dir type=”text” .. />   
  4. </div>  
Both of these ways will work exactly the same way it used to work when we wrote all the template code inside the directive only.

$templateCache

All the template code that we link to our directive resides inside the $templateCache. This $templateCache can be manipulated to "put" and "get" template codes from it.

Long story short, if we remove the template code in the script tag and delete the template file too, the template's code can still be maintained using the $templateCache. See how:
  1. app.run( function ($templateCache) 
  2.    $templateCache.put(“template.html”, “<div>This is template for the directive</div>”); 
  3. });   
We just "put" the template code inside the $templateCache identified by a key "template.html" and we will use it further to get the code by this key inside our directive. We do this by injecting $templateCache into it:
  1. app.directive('myDir'function($templateCache) 
  2.    return 
  3.    { 
  4.       template: $templateCache.get('template.html') }; 
  5. });   
This is still going to work the same as it kept working for us from the start.

That was all I could say about the templates and my next discussion would probably be on routing in AngularJS.

Previous article: AngularJS - Scopes

Up Next
    Ebook Download
    View all
    Learn
    View all