【问题标题】:$sce.trustAsHtml is not evaluating a javascript string (or trustAsJs For that matter);$sce.trustAsHtml 没有评估 javascript 字符串(或 trustAsJs );
【发布时间】:2017-01-14 13:42:55
【问题描述】:

我的服务器有一个 json 端点,它返回一个 html/js 字符串,看起来类似于这样:

"\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..."

我想用 Angular 将这个注入到一个 div 中,并让它也执行 javascript。

第一次尝试:

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>

我注意到,如果我返回一个纯 html 字符串,这些标签会被渲染,但是纯 javascript 标签不会被评估。我如何得到它来评估这些标签? AngularJS 版本 1.5.8。谢谢!

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    您的HTML 存在语法问题,例如 id=\'myEditor\"。我将其替换为 id=\'myEditor\' 等...

    检查此jsfiddleangular.min.jsangular-sanitize.min.js 添加到您的项目中。我在这个示例中使用了jquery 2.2.4

    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!';
    }]);
    

    【讨论】:

      【解决方案2】:

      你必须包含 jQuery 才能工作。也不要忘记 ngSanitize。

      Plunker
      

      http://plnkr.co/edit/zEXXCB459Tp25VJiyyZb?p=preview

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多