2

I am using ng-bind-html but the links in the to binding html won't work.

This is the code for binding the content:

<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>

This is how the link gets compiled Compiled link

the to_trusted filter looks like this:

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

and still, when I click on the link nothing happens. Nothing in the console neither.

Ideas?

Edit: The input string:

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: I should say, the link works completely fine if I right-click it and then click "open in a new tab"

bergben
  • 1,385
  • 1
  • 16
  • 35

2 Answers2

2

The answer is actually quite easy and embarassing.

I had an <a> </a> wrapped around the container where the ng-bind-html got rendered. Changed it to a div. Obviously everything works now.

bergben
  • 1,385
  • 1
  • 16
  • 35
0

How I use it, is I use a compile directive that takes the desired string content, inserts it to the elements and compiles it. It has a high priority of 1000 (default for directives is 0), which means it works before the ng-bind-html directive (higher number -> takes precedence), and then when the ng-bind-html directive runs, it knows that the links are links:

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

The Compile Directive:

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

Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
  • Using this, the link is shown as plain text, not even handled as a link. – bergben Dec 28 '14 at 09:30
  • @Benedikt Take a look now. – Omri Aharon Dec 28 '14 at 09:50
  • Thanks for your help. I tried this, but this is still not working... I think the link is compiled correctly, there is just something from angular that overwrites the browsers click functionality and results into nothing happening... – bergben Dec 28 '14 at 10:05
  • Hey @OmriAharon. Thanks for posting this. It resolved exactly what I was looking for. How were you able to find these features for Angular? I'm not sure I would've been able to solve this myself so I'm wondering what led you to this solution. – a_byte_of_pizza Jan 29 '20 at 20:27