Angular JS - How to handle duplicated HTML code like headers/footers?

前端 未结 4 838
Happy的楠姐
Happy的楠姐 2021-02-01 06:14

I just read the introduction to Angular JS but I didn\'t see anything about a way to code up your HTML header code and footer code just once and have it included in all of your

相关标签:
4条回答
  • 2021-02-01 06:28

    I just found another way to include the same piece of code in multiples views :
    => create and use your own Angular 'directives'

    1) define a directive :

    angular.module('myApp')
      .directive('appfooter', function() {
        return {
          templateUrl: 'widgets/footer.html'
        };
      });
    

    2) create your template called here 'widgets/footer.html'.
    3) use your new directive :

    <div appfooter></div>
    

    References used :

    • AngularJS 'directives' doc
    • Directives usage example

    hope this helps

    0 讨论(0)
  • 2021-02-01 06:41

    The official way to do it is to use ngInclude directive, which "fetches, compiles and includes an external HTML fragment".

    <html ng-app>
    
    <head>
      <script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
    </head>
    
    <body>
      <div ng-include src="'header.url'"></div>
      ...
      <div ng-include src="'footer.url'"></div>
    </body>
    
    </html>

    With this you can reuse the same header.url and footer.url in all your pages.

    0 讨论(0)
  • 2021-02-01 06:41

    I suggest you move your tag to the end of the page to improve app load times since the html loading is not blocked by angular

    </head>
    <body>
       <div ng-include src="header.url"></div>
       ...
       <div ng-include src="footer.url"></div>
    
       <script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
    
    </body>
    

    0 讨论(0)
  • 2021-02-01 06:46

    If you are creating a single-page web application (say, with bookmarkable views/pages using $routeProvider), you can put your header and footer directly into index.html (or use ng-include) and then use ng-view to switch between views/pages:

    <html ng-app>
    <head>
       <script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
    </head>
    <body>
       ... header here, or use ng-include ...
       <div ng-view></div>
       ... footer here, or use ng-include ...
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题