An alternative to inject an AngularJS template by using $templateCache, using .get() and .put() methods
John Lindquist: I briefly mentioned in the previous video that if you create a template and store it in a script tag or load it in or anything, it's going to drop it into a template cache.
Let's look at that real quick. I'm going to inject a template cache here, just a template cache. Then what I can do is just do a console log template cache and then say get. This is just going to look up the key of zippy.html.
If we look at that, you can see it's going to log out the string of what zippy.html is related to. Basically, if you were to do something like this template, it is just template cache, get zippy.html and you will get the same result as we have always got. It still works.
Basically that's what templateUrl is really doing for you. It's just looking that up by key. This is just a key for your template, then dropping it into the template. Just going to change the API so it looks more natural, that the templateUrl is looking for this key. Now if you want to kind of mess around with the template cache, you could do it in the run phase.
Run is when the app is actually downloading all the modules and pretty much everything is ready for you to manipulate. If we take our template cache and instead of having the template inside of here, we can just grab it out. I'm just going to cut that, and delete the script tag. I could just say template cache, put, and then just say the key is zippy.html.
The string is going to be paste on multiple lines, delete the multiple lines so it's all just a string of what we previously had, and then we don't need to log that out any more.
Basically, we remove the template from here and now, we are manually entering the template into the template cache using the zippy.html key and this will still work. This works again. Basically, if you want to do some really funky stuff with loading strings into the template cache, you can do it here. If you ever need to look up any of your templates, you can actually log them all out.
Just by using template cache info will give you some info on what's going on in there, but you'll mainly just use put and get for putting templates in by key using something.html as a standard. You could really use whatever you want for the key, and then using templateUrl is just going to be the shorthand for using that template cache and looking up by key.
'<script type="text/ng-template">...' is a directive (https://docs.angularjs.org/api/ng/directive/script) and app.run executes before directives.
I wonder why we can't get the template in the app.run section, when, for example, we load a template within a ng-template script in the main html file?