本文介绍了$ sce.trustAsHtml并未评估JavaScript字符串(或trustAsJs);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

您的 HTML id = \'myEditor \。我用 id = \'myEditor \'替换了它,然后...



检查此
添加和到您的项目中。 。



HTML:

 < div ng-app =myApp> 
< div ng-controller =myCtrl>
< h2> {{html}}< / h2>
< span> {{greeting}}< / span>
< div ng -bind-HTML = editorHtml >< / DIV>
< / div>
< / div>

JS:

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

var data =\r\\\
\r\\\
< div id = \myEditor \name = \myEditor \> \r\\ \\ n \ \\\\\\\\\\\\\\\\\\\\\\\\&&\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ DIV> \r\\\
\r\\\
\r\\\
\r\\\
\r\t;
var script =< script type = \text / javascript\> alert('hi script'); \r\\\
\r\\\
\t< / +script> \r\\\
\t;
$ b myApp.controller('myCtrl',['$ sce','$ scope',function($ sce,$ scope){
$ scope.html = data + script;
$ scope.editorHtml = $ sce.trustAsHtml($ scope.html);
$ scope.greeting ='Hola!';
}]);


My server has a json endpoint that returns a html/js string, looks similar to such:

"\r\n\r\n<div id=\'myEditor\" name=\"myEditor\">\r\n\r\n\t\t<a href=\"http://example.com\"></a>\r\n\t</div>\r\n\r\n\r\n\r\n\r\t<script type=\"text/javascript\" src=\"/MyEditor/WebResource.axd?...\:">\r\n\r\n\t<script>\r\n\t..."

I want to inject this with angular into a div, and have it execute the javascript as well.

First attempt:

function myCtrl ($sce) {
  $http.get(endpoint).then(function (response) { 
    $scope.html = response.data;
    $scope.editorHtml = $sce.trustAsHtml($scope.html); //also tried trustAsJs
   }
}

html:

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

I noticed that if I return a pure html string those tags get rendered, however a pure javascript tags do NOT get evaluated. How do I get it to evaulate these tags? AngularJS version 1.5.8. Thanks!

解决方案

Your HTML has some syntax problem such id=\'myEditor\". I replaced it with id=\'myEditor\' and so ...

Check this jsfiddleAdd angular.min.js and angular-sanitize.min.js to your project. I used jquery 2.2.4 for this sample.

HTML:

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <h2>{{html}}</h2>
    <span>{{greeting}}</span>
    <div ng-bind-html="editorHtml"></div>
  </div>
</div>

JS:

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

var data = "\r\n\r\n<div id=\"myEditor\" name=\"myEditor\">\r\n\r\n\t\t<a href=\"http://example.com\">hi html</a>\r\n\t</div>\r\n\r\n\r\n\r\n\r\t";
var script = "<script type=\"text/javascript\"> alert('hi script');\r\n\r\n\t</" + "script>\r\n\t";

myApp.controller('myCtrl', ['$sce', '$scope' , function($sce, $scope) {
  $scope.html = data + script;
  $scope.editorHtml = $sce.trustAsHtml($scope.html);
  $scope.greeting = 'Hola!';
}]);

这篇关于$ sce.trustAsHtml并未评估JavaScript字符串(或trustAsJs);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:36