问题
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
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"
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/27675055/links-not-working-in-ng-bind-html