angular.js ng-repeat li项目带有html内容

时间:2013-10-01 08:24:33

标签: javascript html angularjs

我有一个从服务器返回的模型,其中包含html而不是文本(例如b标签或i标签)
当我使用ng-repeat构建一个列表时,它将html显示为纯文本,是否有内置的过滤器或指令将html放在li项目内?我查看了文档,但由于我还是很新,所以我很难找到它。

NG-重复:

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

JSFiddle:

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

7 个答案:

答案 0 :(得分: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代码:Can I use HTML tags in the options for select elements?

答案 1 :(得分:10)

请注意,rc 1.2不再支持ng-bind-html-unsafe。请改用ng-bind-html。请参阅:With ng-bind-html-unsafe removed, how do I inject HTML?

答案 2 :(得分: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内容时你应该非常小心,你应该真正信任内容的来源。

答案 3 :(得分:4)

使用ng-bind-html-unsafe

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

    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}
    </li>

答案 4 :(得分:3)

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

如果您想在原生选项中设置选项样式,请不要这样做。

答案 5 :(得分:3)

以下是官方示例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>

答案 6 :(得分:1)

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

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

<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);
   });
}
相关问题