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>

Webページにファイル「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ディレクティブでは、他のドメインのファイルを含めることはできません。

別のドメインのファイルを含めるには、アプリケーションの構成機能に正当なファイルやドメインのホワイトリストを追加します。

例:

<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>

宛先のサーバーがクロスドメインファイルアクセスを許可していることを確認してください。