ng-bind-html将数据呈现为HTML但忽略子元素

时间:2016-11-25 04:09:47

标签: javascript html css angularjs ng-bind-html

我正在处理这个基于用户输入生成HTML的函数,我可以使用ng-bind-as-html将它作为正确的HTML在列表项(而不是字符串版本)中呈现。

唯一的问题是它不会渲染也是li标签中的子元素的span标记。我是Angular n00b,可以使用任何洞察力。

下面的代码允许我将我的函数输出为正确的HTML,这很好,但我需要显示span标记,因为它允许我的用户复制文本的内容。

基本上,我可以在没有ng-bind-html的情况下重写,并且可以适当地渲染范围,或者我可以使用HTML输出渲染而不是获取span标记。我被困在一个或另一个而不是两个......我想要两个。经典。

感谢您的帮助!

<li 
class="entry"
ng-repeat="entry in output track by $index"
ng-mouseenter="onEnter()"
ng-bind-html="entry">
  {{entry}}
  <span 
    class="copy"
    ng-click="copyData(entry)" 
    ng-mouseenter="onEnter()">
    {{message}}
  </span>
</li>

1 个答案:

答案 0 :(得分:0)

您可以使用directivetransclude创建自定义ng-transclude,以实现此目的。

Documentation for ng-transclude

var app = angular.module('app', []);

app.controller('TestController', ['$scope', function($scope) {
  $scope.message = 'You are welcome!';
  $scope.output = ['<h1>Hello user</h1>'];
}]);

app.directive('bindHtml', ['$sce', function($sce) {
  return {
    restrict: 'A',
    transclude: true,
    template: '<span><span ng-bind-html="html"></span><span ng-transclude></span></span>',
    link: function (scope, element, attrs) {
       scope.html = $sce.trustAsHtml(scope.$eval(attrs.bindHtml));
    }
  };
}]);

angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="TestController">
<li 
class="entry"
ng-repeat="entry in output track by $index"
ng-mouseenter="onEnter()"
bind-html="entry">
  <span 
    class="copy"
    ng-click="copyData(entry)" 
    ng-mouseenter="onEnter()">
    {{message}}
  </span>
</li>
</div>