0

In angular js how can, I render external HTML. I am getting HTML in response from the server. and then storing that HTML in a variable $scope.my_var = res.data and then I want to render that HTML how can I do that. HTML in sample response can be like as follows

"<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <meta http-equiv=\"content-type\" content=\"text/html;charset=UTF-8\">
    <style type=\"text/css\">body {background-color:#fff;}</style>
  </head>
  <body onload=\"return window.document.echoForm.submit()\">
  <form name=\"echoForm\" method=\"POST\" accept-charset=\"UTF-8\">
    <input type=\"hidden\" >
  </form>
  </body>
</html>
\n"

I want to display this HTML content. However, I haved used ngSanitize and ng-bind-html but it is not working for form and input tab only displaying value of title tag

1 Answer 1

1

Normally that should work:

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

Sometimes you also need to trust the source (see $sce).

However, I think it's related to your HTML, because you may not include a whole html with body and head into an existing site (except of using frames or something like that). So I think, you need to strip that down to just the form-part to insert that.

For this issue I compile that code directly to also take advantage of any angular stuff using a dedicated directive.

To give you a hint:

angular.module('myApp')
    .directive('htmlView', function ($compile, $http) {
        return {
            restrict: 'E',
            replace: true,
            link: function (scope, ele, attrs) {
                $http.get("/html-endpoint").then(function (content) {
                            var html = content.data;
                            ele.html(html);
                            $compile(ele.contents())(scope);
                        })
            }
        }
    })
Sign up to request clarification or add additional context in comments.

1 Comment

Would it also be possible to achieve this in a component instead of a directive?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.