AngularJS 包含
使用 AngularJS,您可以包含外部檔案中的 HTML。
AngularJS 包含
使用 AngularJS,您可以使用 ng-include 指令包含 HTML 內容
包含 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.w3schools.com/angular_include.php'"></div>
<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'https://tryit.w3schools.com/**'
]);
});
</script>
</body>
自己動手試一試 »
請確保目標伺服器允許跨域檔案訪問。