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:
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:
- app.directive('myDir', function()
- {
- return
- {
- templateUrl: '~path-to-file/template.html'};
- });
- <div ng-app='myApp'>
- <script type=”text/ng-template” id=”template.html”> <! – template code here --> </script>
- <input my-dir type=”text” .. />
- </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:
$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:
- app.run( function ($templateCache)
- {
- $templateCache.put(“template.html”, “<div>This is template for the directive</div>”);
- });
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:
- app.directive('myDir', function($templateCache)
- {
- return
- {
- template: $templateCache.get('template.html') };
- });
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
That was all I could say about the templates and my next discussion would probably be on routing in AngularJS
Source collected from :http://www.c-sharpcorner.com/UploadFile/2776f9/angularjs-templates-and-templatecache/
No comments :
Post a Comment