Angularjs Template Loading usage detailed _angularjs

Source: Internet
Author: User
Tags http request script tag

The example in this article describes the Angularjs template load usage. Share to everyone for your reference, specific as follows:

Angular template Loading----ng-template

Angularjs, as an MVC (or MVVM) framework, also has the basic concept of template.

The order in which NG loads the templates is loaded---ajax for memory loading.

Memory load

If you have previously used the Bootstrap plug-in's NG version, that is, Angular-ui, you will understand the specific application of this approach. A template is essentially a string that writes a string directly into memory, gets it directly from memory at load, and is faster, and there are two ways to explicitly enable memory loading.

By using $templateCache service to implement

Angular.module (' myApp ', [])
 . Controller (' Myctrl ', [' $scope ', ' $templateCache ', function ($scope, $templateCache) {
    var tmp = '  
 

The $templateCache service put method is responsible for writing the template contents to memory.

Introducing through the script tag

<script type= "Text/ng-template" id= "lovestory.html" >
   
 

Note here that type= "Text/ng-template" is a reference to the NG template, and the id attribute refers to the actual use of the template, and the content between the tags is the actual template content. Also, it should be noted that the ID is definitely not a URL, and this script tag will never send an HTTP request, as discussed in the last detail.

When you actually apply a template, you can get the corresponding data from memory using the ID attribute.

<div ng-include= "' lovestory.html '" class= "OK" ></div>

When using ng-include, it should be noted that the ID is the equivalent of a string, not a ng-expression, so don't forget to add single quotes.

Ajax load

The above memory load, equivalent to a predefined template, defined in Client-side, does not have any interaction with the server, suitable for the low frequency of the template.

When Ng cannot find the corresponding template in memory, the AJAX request is enabled to pull the corresponding template. Suppose the project entry file address is http://127.0.0.1/index.html;

<div ng-include= "' lovestory.html '" class= "OK" ></div>

The same can be used in instructions, templateurl corresponding values

Angular.module (' myApp ', [])
 . Directive (' Templatedemo ', [' $log ', function ($log) {return
  {
  restrict: ' A ', E = Element, A = Attribute, C = Class, M = Comment
  templateurl: ' butterfly.html ',
  replace:true,
  link:func tion ($scope, IELM, Iattrs, controller) {}
  }
 }]

When there is no corresponding template in memory, the AJAX request address is http://127.0.0.1/lovestory.html, the request is successful and the corresponding content is written to $templateCache, the content is not lost when the page is not refreshed and not deleted manually. Also, it's important to remember that Ajax has cache control ...

Memory Template Benefits

In the Yahoo front-end optimization 34, there is a "merge compressed files."

Merge compressed files can reduce the amount of HTTP requests, but also reduce the amount of network traffic, for path dependence is not serious js,css file is absolutely necessary, because each JS,CSS file development, split into different files, to achieve their respective functional needs, on line when merging can, but, HTML files can be compressed, But cannot be merged because the path depends heavily.

Take the personal blog I've done for learning Angularjs: For example, practice routing

Angular.module (' Administratorapp ', [])
 . config (function ($routeProvider, $locationProvider) {
  $ Locationprovider.html5mode (false);
  $routeProvider
   . When ('/manage ', {
    templateurl: ' views/manage.html ',
    controller: ' Managectrl '
   })
   . When ('/diary/:key ', {
    templateurl: ' views/diarydetail.html ',
    controller: ' Diarydetailctrl ',
   } When
   ('/diary ', {
    templateurl: ' views/diarylist.html ',
    controller: ' Diarylistctrl '
   })
   . When ('/publish/:key ', {
    templateurl: ' views/update.html ',
    controller: ' Updatectrl '
   })
   . When ( '/publish ', {
    templateurl: ' views/publish.html ',
    controller: ' Publishctrl '
   }
   . When ('/record ') , {
    templateurl: ' views/record.html ',
    controller: ' Recordctrl '
   })
   . Otherwise ({
    Redirectto: '/diary '
   });
 

Six controllers require six templates, and six HTTP requests load less data than the template resource is seriously wasted. Ng's optimization is to eliminate the path dependence of server-side by replacing the physical path with the virtual path.

The advantage is that a JS file once HTTP request, not six times. The downside is that the memory pressure gets bigger, the PC doesn't matter, and the development of the Web App (mobile) requires some attention.

① Mobile end memory is too brittle, try not to use the predefined template described above, because the template will be loaded into memory

②ajax request finished, will automatically put the results into the cache, so need manual control. The template has a corresponding relationship with the controller, which can be added to the controller inside the following code

$scope. $on (' $locationChangeStart ', function () {
   $templateCache. Remove (' ****.html ');
})

③ $routeProvider template, Templateurl can be functions, the function return value can control template loading.

PS:: I did not involve mobile end development, so here for thinking, and as the mobile phone hardware performance, memory is no longer a problem.

$templateCache method

$templateCache based on Cachefactory, the interface is consistent and can be considered

\ $templateCache = \ $cacheFactory (' template ');

Method function
Put Writing template content to memory
Get Get template content from memory
Remove Pass in key value, delete corresponding template content
RemoveAll Delete all template contents
Destroy Unbind Key-value, but does not free memory
Info Information for the template cache object

Grunt and id attribute misunderstanding

Module.exports = function (grunt) {
 grunt.initconfig {
  html2js: {simple
   : {
    options: {
     base: ', C7/>module: ' Templatestore '
    },
    files: [{
     src: [' views/*.html '],
     dest: ' build/scripts/ Templatestore.js '}}}}
 );
 Grunt.loadnpmtasks (' Grunt-html2js ');
 Grunt.registertask (' Default ', [' html2js ']);
}

This is my current use GRUNT--HTML2JS configuration scheme, the purpose is to put all the template files under the Views folder into the Templatestore module, each template corresponding ID is the path, the generated part of the code is as follows:

Angular.module ("views/diarylist.html", []). Run (["$templateCache", function ($templateCache) {
 $ Templatecache.put ("views/diarylist.html", ' ******* '
}]);

This part of the code is equivalent to

<script type= "Text/ng-template" id= "views/diarylist.html" >
   ***********
</script>

It should now be understood that the ID is only a mark, not a URL ...

Ajax caching

Related content of partial HTTP Header and XHR2 will be introduced as a separate chapter.

I hope this article will help you to Angularjs program design.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.