Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display HTML pages dynamically AngularJS

Hi I couldn't find a working solution properly. Please help me out.

I have a single page application with ui-selects in the page, basically it is for a directory listing. The user will select folders and finally when he/she selects a HTML file in the list, I am generating a url and I have to display the html file in my spa. I was able to display text files, but I don't know how to display html files. I tried ng-bind-html, but don't know how to display that.

I am getting the content of the html using $http.get method and storing the html content in a variable called "contentHTML" I need to display that

like image 421
clearScreen Avatar asked Jul 03 '15 05:07

clearScreen


2 Answers

Your issue is with angular sanitization. It will not let you use ng-bind-html until you stick your HTML content in a special variable that is marked as trusted HTML. Angular makes you do this so that you know that you are very explicitly telling Angular it's okay to render this markup.

It helps protect the average developer from accidentally rendering user input unencoded, which would be very dangerous. You wouldn't want users submitting javascript in input fields and then having your app render that script right into the page somewhere. If it did, the malicious script would run when rendered and could cause all sorts of havoc.

You need to include the ngSanitize module in your app's dependencies.

var app = angular.module('myApp', ['ngSanitize']);

Don't forget to include the angular-sanitize lib in your script references.

<script src="//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-sanitize.js"></script>

Then you need to mark your HTML content as safe to render using the $sce service.

app.controller('myController', function ($scope, $sce) {
  $scope.trustedHtml = $sce.trustAsHtml(contentHTML);
});

Only then will ng-bind-html work.

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

Demo: http://codepen.io/Chevex/pen/xGYydr?editors=101

like image 139
Chev Avatar answered Nov 16 '22 14:11

Chev


I think you're looking for ngInclude.
You don't even need to handle the AJAX request, it's done for you.

Fetches, compiles and includes an external HTML fragment.

Usage

<ANY
  ng-include="path_of_your_file.html"
  [onload="string"]
  [autoscroll="string"]>
  ...
</ANY>

Important things to note:

  • Your HTML file needs to be on the same domain or it gets complicated (see docs)
  • This is a template, which means:
    • All relative paths will be relative to the current path, not to the imported template's path
    • Angular in it will be evaluated
like image 3
Jerska Avatar answered Nov 16 '22 14:11

Jerska