javascript - 在 Angularjs 中使用 ng-bind-html 不显示 html 标签

标签 javascript html angularjs

我有这样的 html 模板:

我想使用“ng-bind-html”绑定(bind)此模板,如下所示:

angular.module('bindHtmlExample', ['ngSanitize'])
  .controller('ExampleController', ['$scope', '$compile',
    function($scope, $compile) {
      var templateHTML =
        'I am an <code>HTML</code>string with ' +
        '<span class="pointer"><i class="icon-refresh pointer" ng-click="refresh()"></i></span>';
      $scope.myHTML = $compile(templateHTML)($scope);
    }
  ]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-sanitize.js"></script>

<div ng-app="bindHtmlExample">
  <div ng-controller="ExampleController">
    <p ng-bind-html-unsafe="myHTML"></p>
    <p ng-bind-html="myHTML"></p>
  </div>
</div>

我什么也没得到。 如何解决这个问题。

最佳答案

我认为这里可能的解决方案是编写自己的指令,例如

angular.module('bindHtmlExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope', '$compile', function ($scope, $compile) {
    var templateHTML =
        '<div>I am an <code>HTML</code>string with ' +
        '<span class="pointer"><i class="icon-refresh pointer" ng-click="refresh()">i</i></span></div>';
    $scope.myHTML = templateHTML;

    $scope.refresh = function () {
        console.log('refresh')
    };
}]);

angular.module('bindHtmlExample').directive('myHtml', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        link: function link($scope, $element, attrs) {
            attrs.$observe('myHtml', function (value) {
                var $el = $compile(value)($scope);
                $element.empty().append($el)
            })
        }
    }
}])
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-sanitize.js"></script>

<div ng-app="bindHtmlExample">
    <div ng-controller="ExampleController">
        <p ng-bind-html-unsafe="myHTML"></p>
        <p ng-bind-html="myHTML"></p>
        <p my-html="{{myHTML}}"></p>
    </div>
</div>

关于javascript - 在 Angularjs 中使用 ng-bind-html 不显示 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26112365/

相关文章:

javascript - 如何将我的 RequireJS main.js 分成两个文件?

javascript - 弹出消息框打开时如何卡住屏幕的其余部分

javascript - 忽略 CSS :hover, :active, :focus declarations with CSS

html - 如何禁用子元素的父元素的设置宽度?

css - 想要获取一个 scss 关联数组并从中生成变量和类

javascript - 逐渐减慢 2D 物体接近

javascript - 在 ng-repeat 中生成 ng-model

javascript - 如何在 JavaScript 中使用五位长的 Unicode 字符

javascript - $.getJSON 解析器错误尝试调用 API

javascript - 无法使用 mqtt.js 通过 tcp 将表单 javascript 连接到代理