【问题标题】:angular bind html tags from controller to html view从控制器到 html 视图的角度绑定 html 标签
【发布时间】:2025-12-01 09:30:01
【问题描述】:

我需要将 $scope.htmlView 标记呈现到 html 视图中。

我已经尝试过使用ng-bind-html。它呈现 html 标签,但范围变量值不会出现。

如何同时呈现 html 标记和范围变量值?

这是控制器:

$scope.newObj = {
  billStatus : true;
  eventTime : "2015-01-10"
};

$scope.htmlView = '<p>{{newObj.eventTime}}</p>    <div style="margin-top: -15px;"><md-checkbox ng-checked="{{newObj.billStatus}}" style="margin-left: 0px;" aria-label="Bilable"><span style="margin-left:0px;">Bilable</span> </md-checkbox></div>'

预期结果是:

<p> 2015-01-10</p> 
<div style="margin-top: -15px;">
  <md-checkbox ng-checked="true" style="margin-left: 0px;" aria- label="Bilable">
    <span style="margin-left:0px;">Bilable</span>
  </md-checkbox>
</div>

我在互联网上搜索了几天,但仍然找不到解决此问题的方法。请帮我。谢谢。

【问题讨论】:

标签: angularjs ng-bind-html


【解决方案1】:

你必须做两件事。

  1. 使用 data-ng-bind-html=""
  2. 使用 $sce.trustAsHtml(string)

更新: 如果您不使用角度表达式,则必须使用

编译它们

$compile.

您可以通过$SCE阅读更多内容

【讨论】:

    【解决方案2】:

    我会告诉你很长的路,但它会帮助你。制作这样的自定义指令。

    app.directive('dynamic', function ($compile) {
    return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
      }
       };
      });
    

    用作

    <span  dynamic="{{htmlView}}" > 
    

    【讨论】:

    • 所以基本上要将字符串转换为 html 模板,我需要使用 $compile。对吧??
    【解决方案3】:

    嗨,请检查这个小提琴 https://plnkr.co/edit/iqNltdDYv2n9Agke0C2C?p=preview

    HTML

      <div ng-controller="ExampleController">
          <p >{{newObj.eventTime}}</p>
           <p dynamic="htmlView"></p>
    </div
    

    和JS

    (function(angular) {
      'use strict';
    angular.module('bindHtmlExample', ['ngSanitize'])
      .controller('ExampleController', ['$scope', function($scope) {
    
           $scope.newObj = {
          billStatus : true,
          eventTime : "2015-01-10"
    }
    
    $scope.htmlView = '<p> {{newObj.eventTime}}</p> <div style="margin-top: -15px;">Hello <md-checkbox ng-checked="{{newObj.billStatus}}" style="margin-left: 0px;" aria-label="Bilable"><span style="margin-left:0px;">Bilable</span> </md-checkbox></div>'
      }])
    
      .directive('dynamic', function($compile) {
        return {
            restrict: 'A',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch(attrs.dynamic, function(html) {
                    element[0].innerHTML = html;
                    $compile(element.contents())(scope);
                });
            }
        };
    });
    })(window.angular);
    

    【讨论】:

    • 你能解释一下ngSanitize的目的吗
    • 那一个不需要,如果你也删除它会正常工作
    最近更新 更多