【问题标题】:Links not working in ng-bind-html链接在 ng-bind-html 中不起作用
【发布时间】:2015-02-24 19:46:28
【问题描述】:

我正在使用 ng-bind-html,但绑定 html 中的链接不起作用。

这是绑定内容的代码:

<div class="list-group-item-text" ng-class="article.img.length >0 ? 'col-md-10' : 'col-md-12'"
                 ng-bind-html="article.content | to_trusted">
</div>

这就是链接的编译方式

to_trusted 过滤器如下所示:

.filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
}])

而且,当我点击链接时,什么也没有发生。控制台中也没有任何内容。

想法?

编辑:输入字符串:

It was never really finished and is actually in a state which is a result of playing around with jQuery and other tools. <a href="http://www.google.com" target="_blank">Google</a>

Edit2:我应该说,如果我右键单击该链接然后单击“在新选项卡中打开”,则该链接完全可以正常工作

【问题讨论】:

  • 你能显示你放入article.content的字符串吗?特别是&lt;a&gt; 部分。
  • 请看编辑,

标签: angularjs ng-bind-html ng-bind


【解决方案1】:

答案其实很简单也很尴尬。

我有一个&lt;a&gt; &lt;/a&gt; 包裹在渲染 ng-bind-html 的容器周围。将其更改为 div。显然现在一切正常。

【讨论】:

    【解决方案2】:

    我如何使用它,是我使用编译指令获取所需的字符串内容,将其插入元素并编译它。它具有 1000 的高优先级(指令的默认值为 0),这意味着它在 ng-bind-html 指令之前工作(更高的数字 -> 优先),然后当 ng-bind-html 指令运行时,它知道链接是链接:

        <div 
             compile-html="text" 
             ng-bind-html="text | to_trusted"></div>
        </div>
    

    编译指令:

    var CompileHtmlDirective = (function () {
        function CompileHtmlDirective($compile) {
            this.$compile = $compile;
            this.priority = 1000;
            this.link = function (scope, element, attr) {
                scope.$watch(attr.compileHtml, function (newVal, oldVal) {
                    if (newVal) {
                        element.html(newVal);
                        $compile(element.contents())(scope);
                    }
                });
            };
        }
    
        return CompileHtmlDirective;
    })();
    

    Here it is in JS Fiddle

    【讨论】:

    • 使用这个,链接显示为纯文本,甚至不作为链接处理。
    • @Benedikt 现在看看。
    • 感谢您的帮助。我试过了,但这仍然不起作用......我认为链接编译正确,只是有一些来自角度的东西覆盖了浏览器的点击功能并导致没有任何事情发生......
    • 嘿@OmriAharon。感谢您发布此信息。它解决了我正在寻找的东西。你是如何为 Angular 找到这些特性的?我不确定我自己是否能够解决这个问题,所以我想知道是什么让你找到了这个解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2015-09-04
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多