简体   繁体   中英

ng-include use for header / footer

New to angular.js I want to use ng-include for header and footer that are common to many pages of my site for easier update

I developped a small very basic example (basic.html) to test this but this is not working

<html ng-app>

  <head>
    <title>Basic Angular.js</title>
    <script src="angular.min.js"></script>
  </head>

  <body>

    <div>
      <label>Name:</label>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <hr>
      <h1>Hello {{yourName}}!</h1>
   </div>

    <div ng-include="'myFile.html'"> Inclusion 1</div>
    <div ng-include src="'myFile.html'"> Inclusion 2</div>

  </body>
</html>

Myfile.html is as follow

<div> 
    <h1> Footer example </h1>
</div>

All files : basic.html, myFile.html and angular.min.js are in the same root directory (that was an issue in other posts related to ng-include errors)

While the first part of the basic.html is working fine (name input and dynamic display with angular) the ng-include is not working in both syntaxes:

    <div ng-include="'myFile.html'">...

or

    <div ng-include src="'myFile.html'"> ...

I did not miss the two consecutive quotes " and ' that were an issue in other posts related to ng-include errors.

I'm at a loss to understand what is the correct syntax or what is missing

Make sure you have angular.module and angular.controller defined. ng-include won't work without them being defined. I hope it helped.

Your code should look like this, note that ng-app="myApp":

 (function(angular){ // create the module and register it to angular var app = angular.module('myApp', []); app.controller("maincontroller", ["$scope"]); }(angular)); 
 <html ng-app="myApp"> <head> <title>Basic Angular.js</title> <!--I'm using the cdn for demo purpose--> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body> <div> <label>Name:</label> <input type="text" ng-model="yourName" placeholder="Enter a name here"> <hr> <h1>Hello {{yourName}}!</h1> </div> <!--both of these syntax should work--> <div ng-include="'myFile.html'"> Inclusion 1</div> <div ng-include src="'myFile.html'"> Inclusion 2</div> </body> </html> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM