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

巧了我就是萌 提交于 2019-12-05 21:37:14

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!