ng-bind-html在我的上下文中不起作用

时间:2015-05-12 12:18:08

标签: javascript jquery angularjs

我正在使用ngBindHtml指令在AngularJS中附加HTML。它附加但不是预期的div中未正确添加的某些区域标记属性。

因此区域标记中的onclick事件无效。首先它不是附加在html中,而是在我使用jQuery .html()它正常工作。 我想要Angular方法的答案。

HTML

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

控制器

 $scope.editor =  "<p>
      <img alt="how to measure" name="shirtguidemeasure" src="http://www.jcpenney.com/dotcom/images/2013_09_SHIRT_TAB1_HOW_TO_MEASURE.jpg" style="width: 620px; height: auto" usemap="#imgmap201310911202" />
      <map id="imgmap201310911202" name="imgmap201310911202">
        <area _fcksavedurl="test" alt="how to measure" coords="5,4,153,31" onclick="document.images.shirtguidemeasure.src='/mobile/images/2013_09_SHIRT_TAB1_HOW_TO_MEASURE.jpg';" shape="rectangle" style="display: block; cursor: pointer" title="how to measure" />
        <area _fcksavedurl="test" alt="classic" coords="157,4,306,31" onclick="document.images.shirtguidemeasure.src='/mobile/images/2013_09_SHIRT_TAB2_CLASSIC.jpg';" shape="rectangle" style="display: block; cursor: pointer" title="classic" />
        <area _fcksavedurl="test" alt="slim" coords="310,3,459,31" onclick="document.images.shirtguidemeasure.src='/mobile/images/2013_09_SHIRT_TAB3_SLIM.jpg';" shape="rectangle" style="display: block; cursor: pointer" title="slim" />
        <area _fcksavedurl="test" alt="big and tall" coords="464,3,617,31" onclick="document.images.shirtguidemeasure.src='/mobile/images/2013_09_SHIRT_TAB4_BIG_TALL.jpg';" shape="rectangle" style="display: block; cursor: pointer" title="big and tall" />
      </map>
     </p>";

输出

<div ng-bind-html="editor" class="ng-binding">
<p>
<img alt="how to measure" src="http://www.jcpenney.com/dotcom/images/2013_09_SHIRT_TAB1_HOW_TO_MEASURE.jpg" usemap="#imgmap201310911202">
<map>
<area alt="how to measure" coords="5,4,153,31" shape="rectangle" title="how to measure">
<area alt="classic" coords="157,4,306,31" shape="rectangle" title="classic">
<area alt="slim" coords="310,3,459,31" shape="rectangle" title="slim">
<area alt="big and tall" coords="464,3,617,31" shape="rectangle" title="big and tall">
</map>
</p>
</div>

在输出缺失区域标记属性onclick="document.images.shirtguidemeasure.src和样式。

2 个答案:

答案 0 :(得分:1)

ng-bind-html正在使用$sanitize服务进行清理。作为其中的一部分,一些不安全的令牌将从输出中删除。在较早版本的Angular中,您可以使用ng-bing-html-unsafe代替:

<div ng-bind-html-unsafe="editor"></div>

此指令在更高版本的angular中不存在,因此您需要通过$ sce.trustAsHtml显式信任值。请参阅Strict Contextual Escaping (SCE)下的示例。

在这种情况下,在控制器中,您需要为$sce添加依赖项,并使用它将HTML标记为安全:

angular.module('mySceApp', ['ngSanitize'])
    .controller('AppController', function($scope, $sce) {
            $scope.editor = $sce.trustAsHtml('YOUR UNSAFE HTML GOES HERE');
        }
    );

答案 1 :(得分:0)

我认为你正在混合单引号和双引号用法, 加上多行的HTML应该引用:

$scope.editor =  
  '<p>'+
  '<h1 style="color: red;">MY HEADER</h1>'+
  '</p>';