AngularJS 包含

AngularJS 教程 · 2019-04-01 08:56:56

在 AngularJS 中,你可以在 HTML 中包含 HTML 文件。

在 HTML 中包含 HTML 文件

在 HTML 中,目前还不支持包含 HTML 文件的功能。

服务端包含

大多服务端脚本都支持包含文件功能 (SSI: Server Side Includes)。

使用 SSI, 你可在 HTML 中包含 HTML 文件,并发送到客户端浏览器。

PHP 实例

<?php require("navigation.php"); ?>

客户端包含

通过 JavaScript 有很多种方式可以在 HTML 中包含 HTML 文件。

通常我们使用 http 请求 (AJAX) 从服务端获取数据,返回的数据我们可以通过 使用 innerHTML 写入到 HTML 元素中。

AngularJS 包含

使用 AngularJS, 你可以使用 ng-include 指令来包含 HTML 内容:

实例

<body ng-app=""> <div ng-include="'codercto.htm'"></div> </body>

步骤如下:

codercto.htm 文件代码:

<h1>码农教程</h1> <p>这是一个被包含的 HTML 页面,使用 ng-include 指令来实现!</p>

包含 AngularJS 代码

ng-include 指令除了可以包含 HTML 文件外,还可以包含 AngularJS 代码:

sites.htm 文件代码:

<table> <tr ng-repeat="x in names"> <td>{{ x.Name }}</td> <td>{{ x.Url }}</td> </tr> </table>

包含的文件 "sites.htm" 中有 AngularJS 代码,它将被正常执行:

实例

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

跨域包含

默认情况下, ng-include 指令不允许包含其他域名的文件。

如果你需要包含其他域名的文件,你需要设置域名访问白名单:

sites.htm 文件代码:

<body ng-app="myApp"> <div ng-include="'https://c.codercto.com/coderctotest/angular_include.php'"></div> <script> var app = angular.module('myApp', []) app.config(function($sceDelegateProvider) { $sceDelegateProvider.resourceUrlWhitelist([ 'https://c.codercto.com/coderctotest/**' ]); }); </script> </body>

此外,你还需要设置服务端允许跨域访问,设置方法可参考:PHP Ajax 跨域问题最佳解决方案。

angular_include.php 文件代码:

<?php // 允许所有域名可以访问 header('Access-Control-Allow-Origin:*'); echo '<b style="color:red">我是跨域的内容</b>'; ?>

点击查看所有 AngularJS 教程 文章: https://www.codercto.com/courses/l/36.html

查看所有标签

Programming From The Ground Up

Programming From The Ground Up

Jonathan Bartlett / Bartlett Publishing / 2004-07-31 / USD 34.95

Programming from the Ground Up is an introduction to programming using assembly language on the Linux platform for x86 machines. It is a great book for novices who are just learning to program as wel......一起来看看 《Programming From The Ground Up》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具