【问题标题】:Angular directive for customized html tag in table表格中自定义 html 标记的 Angular 指令
【发布时间】:2014-07-31 23:23:59
【问题描述】:

我得到了一个解决方案,使用 AngularJS 指令让 html 将我的标签 bold 理解为 html 标签 b。所以<bold>{{testWorks}}</bold> 会在我的范围内有 textWorks 时将文本样式设置为粗体。

但是,当我有 {{testText}} 时它不起作用:$scope.testText = "<bold>Peter</bold>";

当我使用ng-bind-html让值被评估为html时也不起作用,你可以从Plunker找到代码

会不会是在计算表达式之前应用了指令?

【问题讨论】:

  • 对于这样的事情,您可能应该使用类过滤器,而不是元素过滤器。然后你可以做<div class="directiveClass">Text<div/>

标签: javascript angularjs directive ng-bind-html


【解决方案1】:

为了将一些 html 绑定到一个角度变量,您必须使用 $sce 模块来验证内容。

现场样本: http://plnkr.co/edit/NBFsepObvv5IujigTosK?p=preview

.controller('myController', ['$scope', '$sce', function($scope, $sce) {
    $scope.testText = $sce.trustAsHtml("<bold>Peter</bold>");

}]);

【讨论】:

    【解决方案2】:

    您可能需要将控制器更改为以下

    .controller('myController', ['$scope', '$sce', function($scope, $sce) {
          $scope.testWorks = 'John';
          $scope.testText = $sce.trustAsHtml("<bold>Peter</bold>");
          $scope.testTable = [$sce.trustAsHtml('<bold>A</bold>'), $sce.trustAsHtml('<bold>B</bold>'), $sce.trustAsHtml('<bold>C</bold>')];
        }]);
    

    然后你 html 到:

    <tr>
        <td ng:repeat="data in testTable" ng-bind-html="data"> </td> 
    </tr>
    

    here is an example

    【讨论】:

      【解决方案3】:

      感谢 Polochonrishal,我得到了 $sce.trustAsHtml($compile("&lt;bold&gt;A&lt;/bold&gt;")($scope).html() 的帮助。你可以从这里找到它:Plunker

      【讨论】:

      • 嗨,编译创建一个“jquery”节点,让您可以访问附加和前置功能。当您想在页面加载后向 DOM 添加指令时需要它。但是,如果您使用角度变量,则无需在添加之前进行编译。只需使用 trustAsHtml。
      猜你喜欢
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多