I'm using ng-bind-html to put up some HTML content on my site. The problem is if the content has links, the links open in the same window when clicked. How can I make it open in a new window?
<div ng-bind-html="currentElement.content"></div>
links contained in your currentElement.content should have the attribute target='_blank'
<a href="open/me/in/new/window" target="_blank">MyLink</a>
if the html content comes from an external source, you could add a filter that parses the html content and adds the target attribute to links
this is a sketch:
return angular.element(htmlContent).find('a').attr('target', '_blank');
more in details
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="angular-sanitize@*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular-sanitize.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="test" ng-controller="HomeCtrl">
<h1>Test </h1>
<div ng-bind-html="myHtml | addTargetBlank"></div>
</body>
</html>
//script.js
angular.module('test', ['ngSanitize'])
.filter('addTargetBlank', function(){
return function(x) {
var tree = angular.element('<div>'+x+'</div>');//defensively wrap in a div to avoid 'invalid html' exception
tree.find('a').attr('target', '_blank'); //manipulate the parse tree
return angular.element('<div>').append(tree).html(); //trick to have a string representation
}
})
.controller('HomeCtrl', function($scope){
$scope.myHtml = 'test html content 1 <a href="#">click here</a>, test html content 2 <a href="#">click here</a>, test html content 3 <a href="#">click here</a>';
})
;
来源:https://stackoverflow.com/questions/25303615/ng-bind-html-how-do-i-make-links-open-in-a-new-window