$ templateCache, $ templateRequest, ngInclude play nice (er) together

I am trying to get all my partial parts in the first view of the page, so that when viewing the application html is not loading.

One way is to have templates in index.html .

 <script type="text/ng-template" id="templateId.html"> <p>This is the content of the template</p> </script> 
  • Thus, you have more than 5 templates. index.html file becomes unmanageable and breaks down the modular structure of the project.

Another way to do this is to have html in the .js file, most likely in app.js

 myApp.run(function($templateCache) { $templateCache.put('templateId.html', 'This is the content of the template'); }); 
  • I think the .js file is not the place for HTML code and again the same problems as with the fact that it is in index.html .

What I would like to do is have templates in different files, so I can save the structure of my modules and preload them by index.

This is what I have now.

 var cmsAppFirstRun = function ($templateCache, $templateRequest, $rootScope) { $templateRequest('views/common/top-bar.html').then(function (response) { $templateCache.put('top.bar', response); $rootScope.templatesDone = true; }); }; angular.module('cmsApp').run(cmsAppFirstRun); 

And html

 <div ng-include="'top.bar'" ng-if="$root.templatesDone"></div> 

Is there a sexier, angular way to do this?

+6
source share
2 answers

Several methods were found using $http and $route in stack responses .

I think the most attractive is

 angular.module('MyApp', []) .run(function ($templateCache, $route, $http) { var url; for(var i in $route.routes) { if (url = $route.routes[i].templateUrl) { $http.get(url, {cache: $templateCache}); } } }) 

Thus, all the templates in the route are loaded at the first start.


EDIT: I am using a UI Router , so the thing looks a little different in the angular.run() block. Nested views are not yet processed.

 angular.forEach($state.get(), function(state){ if(state.templateUrl){ $http.get(state.templateUrl, {cache: $templateCache}); } }); 

EDIT 2: I skipped $ templateRequest, which could be the path to the html template in the angular.run() block.

  $templateRequest('views/cart/modal-confirm-continue-printing.html'); $templateRequest('views/cart/modal-confirm-trash.html'); 

EDIT 3: Since I am creating grunt applications, I find https://www.npmjs.com/package/grunt-angular-templates usefoul to automate this process.

+2
source

I'm not sure it can help you, but in my project I used gulp-ngtemplate to create a js file with all html files like "$ templateCache.put ()".

+1
source

Source: https://habr.com/ru/post/983852/


All Articles