Easy Tutorial
❮ Ng Ng App Ng Ng Src ❯

AngularJS include


In AngularJS, you can include HTML files within your HTML.


Including HTML Files in HTML

Currently, HTML does not support the inclusion of HTML files.


Server-Side Includes

Most server-side scripts support the inclusion of files (SSI: Server Side Includes).

Using SSI, you can include HTML files in your HTML and send them to the client's browser.

PHP Example

<?php require("navigation.php"); ?>

Client-Side Includes

There are many ways to include HTML files in your HTML using JavaScript.

Typically, we use HTTP requests (AJAX) to fetch data from the server, and the returned data can be inserted into HTML elements using innerHTML.


AngularJS Include

With AngularJS, you can use the ng-include directive to include HTML content:

Example

<body ng-app="">

<div ng-include="'tutorialpro.htm'"></div>

</body>

Steps are as follows:


tutorialpro.htm File Code:

<h1>tutorialpro.org</h1>
<p>This is an included HTML page, implemented using the ng-include directive!</p>

Including AngularJS Code

The ng-include directive can include not only HTML files but also AngularJS code:

sites.htm File Code:

<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Url }}</td>
</tr>
</table>

The included file "sites.php" contains AngularJS code, which will be executed normally:

Example

<div ng-app="myApp" ng-controller="sitesCtrl"> 
  <div ng-include="'sites.htm'"></div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('sitesCtrl', function($scope, $http) {
    $http.get("sites.php").then(function (response) {
        $scope.names = response.data.records;
    });
});
</script>

Cross-Domain Includes

By default, the ng-include directive does not allow including files from other domains.

If you need to include files from other domains, you need to set up a domain access whitelist:

sites.htm File Code:

<body ng-app="myApp">

<div ng-include="'https://c.tutorialpro.org/tutorialprotest/angular_include.php'"></div>

<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        'https://c.tutorialpro.org/tutorialprotest/**'
    ]);
});
</script>

</body>

Additionally, you need to set up the server to allow cross-domain access. For the setup method, refer to: PHP Ajax Cross-Domain Best Solution.

angular_include.php File Code:

<?php
// Allow all domains to access
header('Access-Control-Allow-Origin:*');

echo '<b style="color:red">I am cross-domain content</b>';
?>
❮ Ng Ng App Ng Ng Src ❯