Currently am working on a big html file(7k+ lines of code). I have to refactor the whole thing. Person previously responsible for the code was using a method presented below to load specific templates into cache to be used via ng-include.
<script type="text/ng-template" id="app/templates/example.html">
<p>Example</p>
</script>
Those templates also exist as separate html files.
My first idea was to use
$templateCache.put(url,content)
method during module.run() stage. It would be a perfect solution, if I could somehow pass template-url-path as a second parameter(content) instead of passing actual html code.
Or perhaps should I just add templates via directive.templateUrl ?
Thank You in advance!
Unless it is important for you to have those templates cached once the app initially loads then I would just place those templates into their own files and put that templateUrl on those directives or routes.
Edit:
Angular will do a call for the template once during the lifespan of the application when that particular route or directive loads, and after that Angular will only go to the $templateCache
service. So if you just specify a templateUrl
on your directive, once that directive loads for the first time Angular will do an ajax call for that template and then store it in $templateCache
for you. So having 100 directives on the page that use the templateUrl
of views/user.html
will do a call for that template once and then never again until the page completely reloads.
If using grunt-angular-templates or gulp-angular-templatecache like Dan said is an option then I would go with that, especially for production builds.
Keep in mind though when using grunt-angular-templates, if you have a directive that references a templateUrl like /views/main.html
and your have views/main.html
loaded into your $templateCache
, angular won't know to use it by default because it's missing the leading slash.
这可能不是您想要的,但是如果您使用诸如Gulp
或Grunt
这样的构建系统,则可能会使用诸如gulp-angular-templatecache之类的东西,它基本上将所有模板打包,将它们放入$templateCache
并制作出templates
模块您只需将它们添加为对应用程序的依赖项即可。
I compile all my templates to one templates.js file with with grunt html2js task.
Recommend to have a look
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.