angular 将 html 标签从控制器绑定到 html 视图

angular bind html tags from controller to html view

我需要在 html 视图中呈现 $scope.htmlView 标签。

我已经尝试使用 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>

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

你必须做两件事。

  1. 使用数据-ng-绑定-html=""
  2. 使用 $sce.trustAsHtml(字符串)

更新: 如果你不想使用 angular 表达式,你必须使用

来编译它们

$compile.

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

我会告诉你很长的路要走,但它会帮助you.Make像这样的自定义指令。

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}}" > 

您好,请检查一下 fiddle 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);