【问题标题】:Failing to load html file dynamically and parsing all angularjs directives in html file无法动态加载 html 文件并解析 html 文件中的所有 angularjs 指令
【发布时间】:2015-03-04 12:05:14
【问题描述】:

所以我建立了一个网站,我希望将其他 .html 文件动态加载到一个 div 中。每个 .html 文件都包含一些内容,但 1 个 .html 文件包含自己的 angularjs 指令。

我使用 ng-bind-html$scope.content = $sce.trustAsHtml(data); 但我发现这会打印出 html raw(不处理任何角度指令)。

我尝试使用各种解决堆栈溢出问题的解决方案,但没有一个对我有用。

网址:http://algorithmictrading.azurewebsites.net/

App.js:http://algorithmictrading.azurewebsites.net/js/app.js

正在加载的 .html 页面示例: http://algorithmictrading.azurewebsites.net/includes/home.html http://algorithmictrading.azurewebsites.net/includes/about_us.html

.html 包含角度指令的页面: http://algorithmictrading.azurewebsites.net/includes/download.html

如您所见,如果您导航到网站并单击“下载”选项卡,则会加载内容,但不会处理下拉菜单中的角度。我添加的测试按钮也应该会产生一个警告框。

现在,代码基于此线程: call function inside $sce.trustAsHtml() string in Angular js

谢谢!

【问题讨论】:

    标签: html angularjs controller angularjs-compile


    【解决方案1】:

    我发现,如果我在将指令传递到模板之前没有通过 $sce.trustAsHtml 方法传递指令,那么 Angular 会从 html 字符串中删除指令:

    $sce.trustAsHtml('<a href="/some-link" directive-example>link to add</a>');
    

    这与您插入 html 的元素内容的监视/编译相结合似乎可以解决问题:

    scope.$watch(getStringValue, function() {
        $compile(element, null, -9999)(scope);    
    });
    

    看看这个例子:http://plnkr.co/edit/VyZmQVnRqfIkdrYgBA1R?p=preview

    【讨论】:

    • 保罗的回答很好!完美运行。谢谢!
    【解决方案2】:

    本周遇到了同样的问题,我发现让它工作的最好方法是创建一个名为“BindComponent”的自定义指令。 将 ng-bind-html 指令更改为自定义指令,并在链接方法中放置以下内容:

    element.html(markupModel);
    $compile(element.contents())(scope);
    

    markupModel 可以是带有 html 代码的字符串,也可以使用 $templateCache($templateCache docs) 从 .html 文件中获取代码。

    【讨论】:

    • 我看到了 templateCache 的作用,所以我可以用它来存储我的 html,但我不明白你所说的自定义指令是什么意思。你有文档或任何示例代码吗?
    • 自定义指令 = 您创建的任何指令,而不是角度指令(ng-bind-html、ng-click、ng-src、ng-...。一切都是指令)。例如,只需创建一个 angular.module('app', []).directive('bindComponent', function(){}) 并在 html 元素中为 bind-component 调整 ng-bind-html。它几乎是 jQuery 的方式,但使用 $compile 来创造魔法。 jsfiddle.net/q13xo73h 我的代码片段 :) 一些文档:docs.angularjs.org/guide/directive
    • component_element 值是一些随机的 html("
      "),但可能类似于:component_element = $templateCache('template.html')
    • 不幸的是,我尝试了这个但没有运气。在 index.html 中有
      ,这是 app.js :pastebin.com/raw.php?i=n1awxbZS 我是否使用了不正确的指令?我也尝试将它添加到控制器中。
    • 所以我的指令名称有误。修复该问题后,我可以获取 html 来显示我是否最初将其存储在页面加载中,但是当我单击导航栏上的选项卡时,如何获取要调用的指令?
    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2012-08-02
    • 2016-02-24
    • 2020-03-25
    • 2011-06-12
    • 2021-09-29
    相关资源
    最近更新 更多