棱角分明.js NG重复的带有HTML内容的LI项目

angular.js ng-repeat li items with html content

本文关键字:HTML 项目 LI js NG      更新时间:2023-09-26

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

ng-重复:

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

JSFiddle:

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

它像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 标记吗?

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

您可以使用 NGBindHTML 或 NGbindHtmlUnsafe 这不会逃脱模型的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内容时应该非常小心,您应该真正信任内容的来源。

使用ng-bind-html-unsafe

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

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

这是来自官方示例 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>

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

如果要在本机选择中设置选项样式,则不,这是不可能的。

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);
   });
}