33

I have a model that comes back from the server which contains html instead of text (for instance a b tag or an i tag)
when I use ng-repeat to built a list out of it it shows the html as pure text, is there a built in filter or directive that put's the html inside the li items or not?
I've looked in the documentation but since I'm still very new to it I'm having difficulties finding it.

ng-repeat:

    <li ng-repeat="opt in opts">

JSFiddle:

http://jsfiddle.net/gFFBa/1/

4

7 回答 7

44

它是这样的ng-bind-html-unsafe="opt.text"

<div ng-app ng-controller="MyCtrl">
    <ul>
    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}
    </li>
    </ul>

    <p>{{opt}}</p>
</div>

http://jsfiddle.net/gFFBa/3/

或者您可以在范围内定义一个函数:

 $scope.getContent = function(obj){
     return obj.value + " " + obj.text;
 }

并以这种方式使用它:

<li ng-repeat=" opt in opts" ng-bind-html-unsafe="getContent(opt)" >
     {{ opt.value }}
</li>

http://jsfiddle.net/gFFBa/4/

请注意,您不能使用option标记来执行此操作:我可以在选择元素的选项中使用 HTML 标记吗?

于 2013-10-01T08:37:09.757 回答
11

请注意,rc 1.2 不再支持 ng-bind-html-unsafe。请改用 ng-bind-html。请参阅:删除 ng-bind-html-unsafe 后,如何注入 HTML?

于 2014-08-27T14:25:56.607 回答
8

您可以使用NGBindHTMLNGbindHtmlUnsafe这不会逃避html模型的内容。

http://jsfiddle.net/n9rQr/

<div ng-app ng-controller="MyCtrl">
    <ul>
    <li ng-repeat=" opt in opts"  ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
    </li>
    </ul>

    <p>{{opt}}</p>
</div>

这行得通,无论如何你在使用unsanitized html内容时应该非常小心,你应该真正相信内容的来源。

于 2013-10-01T08:33:01.103 回答
4

利用ng-bind-html-unsafe

它将应用带有文本的html,如下所示:

    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}
    </li>
于 2013-10-01T08:47:35.400 回答
4

这是来自官方示例angular docs v1.5 的指令,它显示了如何编译 html:

.directive('compileHtml', function ($compile) {
  return function (scope, element, attrs) {
    scope.$watch(
      function(scope) {
        return scope.$eval(attrs.compileHtml);
      },
      function(value) {
        element.html(value);
        $compile(element.contents())(scope);
      }
    );
  };
});

用法:

<div compile-html="item.htmlString"></div>

它将 item.htmlString 属性作为 html 插入任何地方,例如

<li ng-repeat="item in itemList">
    <div compile-html="item.htmlString"></div>
于 2016-03-09T09:23:59.290 回答
3

如果您希望某个元素包含 HTML 值,请查看ngBindHtmlUnsafe

如果您想在本机选择中设置选项样式,那么这是不可能的。

于 2013-10-01T08:31:24.453 回答
1

ng-bind-html-unsafe 从 1.2 开始被弃用。目前正确答案应该是:

HTML端:(与接受的答案相同):

<div ng-app ng-controller="MyCtrl">
   <ul>
      <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
      </li>
   </ul>

   <p>{{opt}}</p>
</div>

但在控制器端:

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
   $scope.opts.map(function(opt) { 
      opt = $sce.trustAsHtml(opt);
   });
}
于 2015-08-14T18:31:13.647 回答