javascript - 带有 UI Bootstrap 指令的 ng-bind-html

标签 javascript angularjs angularjs-directive angular-ui-bootstrap

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

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

JavaScript

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

我要注入(inject)的 HTML 是:

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

有什么线索吗?

最佳答案

这是因为 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>

关于javascript - 带有 UI Bootstrap 指令的 ng-bind-html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28465352/

相关文章:

javascript - 异步函数中没有执行代码

javascript - Chart.js 水平条网格线颜色

javascript - 如何在 Angular 的 promise 之外获取变量?

angularjs - AngularStack Facebook、Google+ 和 Twitter 身份验证

angularjs - 为什么这个具有可变对象名称的 AngularJs 服务返回一个 undefined object ?

javascript - 让 Angular 检测 $scope 中的变化

javascript - 将 jQuery 代码翻译为 Google 跟踪代码管理器的纯 JavaScript

javascript - 如何在 javascript 中过滤 2 个列表之间的项目?

javascript - 如何找到等待 promise 的 JavaScript 代码

javascript - Angular Directive(指令) : template from other file