首页 > 代码库 > AngularJS学习篇(二十)
AngularJS学习篇(二十)
AngularJS 包含
在 AngularJS 中,你可以在 HTML 中包含 HTML 文件。
使用 AngularJS, 你可以使用 ng-include 指令来包含 HTML 内容:
<body ng-app=""> <div ng-include="‘test.htm‘"></div> </body>
test.htm 文件代码:
<h1>菜鸟教程</h1> <p>这是一个被包含的 HTML 页面,使用 ng-include 指令来实现!</p>
ng-include 指令除了可以包含 HTML 文件外,还可以包含 AngularJS 代码:
<!DOCTYPE html> <html> <meta charset="utf-8"> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="sitesCtrl"> <div ng-include="‘sites.htm‘"></div> </div> <script> var app = angular.module(‘myApp‘, []); app.controller(‘sitesCtrl‘, function($scope, $http) { $http.get("sites.php").then(function (response) { $scope.names = response.data.records; }); }); </script> <p>AngularJS 代码包含在 "sites.htm" 文件中。</p> </body> </html>
sites.htm 文件代码:
<table> <tr ng-repeat="x in names"> <td>{{ x.Name }}</td> <td>{{ x.Url }}</td> </tr> </table>
跨域包含
默认情况下, ng-include 指令不允许包含其他域名的文件。
如果你需要包含其他域名的文件,你需要设置域名访问白名单:
<!DOCTYPE html> <html> <meta charset="utf-8"> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <body ng-app="myApp"> <div ng-include="‘http://c.runoob.com/runoobtest/angular_include.php‘"></div> <script> var app = angular.module(‘myApp‘, []) app.config(function($sceDelegateProvider) { $sceDelegateProvider.resourceUrlWhitelist([ ‘http://c.runoob.com/runoobtest/**‘ ]); }); </script> <p>你需要设置服务端允许跨域访问,设置方法可参考 <a target="_blank" href="/w3cnote/php-ajax-cross-border.html">PHP Ajax 跨域问题最佳解决方案</a>。 </body> </html>
此外,你还需要设置服务端允许跨域访问,设置方法可参考:PHP Ajax 跨域问题最佳解决方案。
<?php // 允许所有域名可以访问 header(‘Access-Control-Allow-Origin:*‘); echo ‘<b style="color:red">我是跨域的内容</b>‘; ?>
AngularJS学习篇(二十)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。