ng-bind-html - how do I make links open in a new w

2019-05-11 10:23发布

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>

1条回答
一夜七次
2楼-- · 2019-05-11 10:48

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>';
})
;

http://plnkr.co/edit/tpl:JHcBgtJ75fVaqFYQlE4a

查看更多
登录 后发表回答