简体   繁体   中英

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.

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

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

Problem :

At that time, the html content is loaded. 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 :

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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