AngularJS 包含
使用 AngularJS,可以从外部文件中包含 HTML。
AngularJS 包含
使用 AngularJS,可以使用 ng-include 指令包含 HTML 内容:
实例
<!DOCTYPE html><html><script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script><body ng-app=""><div ng-include="'myFile.htm'"></div></body></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 代码都将被执行,甚至包括包含文件中的代码:
实例
<!DOCTYPE html><html><script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script><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><p>该表的 HTML 和 AngularJS 代码位于文件 "myTable.htm" 中。</p></body></html>
包含跨域
默认情况下,ng-include 指令不允许包含来自其他域的文件。
要包含来自其他域的文件,可以在应用程序的配置功能中添加合法文件和/或域的白名单:
Example:
<!DOCTYPE html><html><script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script><body ng-app="myApp"><div ng-include="'https://cankaoshouce.com/angular_include.php'"></div><script>var app = angular.module('myApp', [])app.config(function($sceDelegateProvider) {$sceDelegateProvider.resourceUrlWhitelist(['https://cankaoshouce.com/**']);});</script></body></html>
确保目标服务器允许跨域文件访问。