AngularJS 包含
- 上一頁 AngularJS API
- 下一頁 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.codew3c.com/angular_include.php'"></div> <script> var app = angular.module('myApp', []) app.config(function($sceDelegateProvider) { $sceDelegateProvider.resourceUrlWhitelist([ 'https://tryit.codew3c.com/**' ]); }); </script> </body>
請確保目標服務器允許跨域文件訪問。
- 上一頁 AngularJS API
- 下一頁 AngularJS 動畫