AngularJS 包含

使用 AngularJS,您可以包含外部文件中的 HTML。

AngularJS 包含

使用 AngularJS,您可以使用 ng-include 指令包含 HTML 内容:

实例

<body ng-app="">

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

</body>

亲自试一试

包含 AngularJS 代码

您使用 ng-include 指令包含的 HTML 文件也可以包含 AngularJS 代码:

myTable.htm:
<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

在您的网页中包含 "myTable.htm" 文件,所有 AngularJS 代码都将被执行,即使是包含文件中的代码:

实例

<body>

<div ng-app="myApp" ng-controller="customersCtrl">
  <div ng-include="'myTable.htm'"></div>
</div>

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

亲自试一试

跨域包括

默认情况下,ng-include 指令不允许您包含来自其他域的文件。

要包含来自另一个域的文件,您可以在应用程序的 config 函数中添加合法文件和/或域的白名单:

实例

<body ng-app="myApp">

<div ng-include="'https://tryit.w3school.com.cn/angular_include.php'"></div>

<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'https://tryit.w3school.com.cn/**'
  ]);
});
</script>

</body>

亲自试一试

请确保目标服务器允许跨域文件访问。