简体   繁体   English

在javascript中加载html内容

[英]Load html content in javascript

What I'm trying to do : 我正在尝试做什么:

I'm working on an Angular SPA, and I'd like to load some html content in a scope in order to display it. 我正在开发一个Angular SPA,我想在一个scope加载一些html内容以显示它。

What I did : 我做了什么 :

According to SO questions ( here and here ), I create a function which loads the targeted file and I load its content in my scope (code is from Jason Sturges suggestion) : 根据SO问题( 这里这里 ),我创建了一个加载目标文件的函数,并将其内容加载到我的scope (代码来自Jason Sturges建议):

 function loadPage(href) {

      var xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", href, false);
      xmlhttp.send();
      return xmlhttp.responseText;
 }

Used with : $scope.pageContent = loadPage("html_file.html") 用于: $scope.pageContent = loadPage("html_file.html")

Problem : 问题:

At that time, the html content is loaded. 那时,加载了html内容。 The problem is that, instead of being interpreted by Chrome, it appears as 'plain text' (I guess it's the right term for that), like this : 问题是,它不是由Chrome解释,而是显示为“纯文本”(我猜这是正确的术语),如下所示:

 <div><h4>...</h4></div>

What should I do ? 我该怎么办 ?

Depending on your angularJs version, it can change, but based on angular 1.3, you should use the ng-bind-html directive with the $sce service : 根据您的angularJs版本,它可以更改,但基于角度1.3,您应该使用ng-bind-html指令和$ sce服务:

In template : 在模板中:

<div ng-bind-html="securedHtml"></div>

In controller : 在控制器中:

$scope.securedHtml= $sce.trustAsHtml(yourRawHtmlFromServer);

And like the other answer said, use the internal $http service (or ngResource ) to make your ajax calls. 和其他答案一样,使用内部$ http服务(或ngResource )来进行ajax调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM