ng使用UI引导指令绑定html

ng-bind-html with UI Bootstrap directives

本文关键字:指令 绑定 html 使用 UI ng      更新时间:2023-09-26

我不认为这是一个直接的问题,但我不知道如何做到这一点。我试图动态加载使用UI Bootstrap指令的内容,但当加载内容时,UI Bootsrap组件不起作用。更具体地说,工具提示不起作用。这是重要的代码:

<div ng-bind-html="trustSnippet(f.field.contentAfter)"></div>

javascript

$scope.trustSnippet = function(snippet) {
          return $sce.trustAsHtml(snippet);
};

我试图注入的HTML是:

<i class="fa fa-exclamation-circle" tooltip-placement="right" tooltip="On the Right!"></i>

有线索吗?

TY

这是因为ng-bind-html不编译插入的元素,因此UI Bootstrap指令或任何其他指令或表达式都不起作用。

如果您从特定位置获取HTML,您可以简单地使用ng-include

对于静态位置:

<div ng-include="'path/to/html'"></div>

或者,如果位置是动态的并且存储在范围暴露变量中:$scope.path = "path/to/html";:

<div ng-include="path"></div>

否则,如果带有Angular表达式/指令的HTML本身是动态生成或导入的(这是一种罕见的情况,应该会让你重新检查你的设计,以确保你没有违反任何最佳实践),你需要使用$compile服务来编译它,最好使用一个指令:

app.directive("ngBindHtmlCompile", function($compile, $sce){
  return {
    restrict: "A",
    link: function(scope, element, attrs){
      scope.$watch($sce.parseAsHtml(attrs.ngBindHtmlCompile), function(html){
        var el = angular.element("<div>").html(html);
        element.empty();
        element.append(el.children());
        $compile(element.contents())(scope);
      })
    }
  };
});

不要忘记添加"ngSanitize"作为依赖项。用法是:

<div ng-bind-html-compile="html"></div>

我也面临同样的问题。以下方法对我有效。

在HTML中,

<div ng-bind-html="f.field.contentAfter | unsafe"></div>

在Javascript中,

app.filter('unsafe', function($sce) {
  return function(val) {
      return $sce.trustAsHtml(val);
  }; 
});