ng-bind-html-如何在新窗口中打开链接? [英] ng-bind-html - how do I make links open in a new window?

查看:67
本文介绍了ng-bind-html-如何在新窗口中打开链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ng-bind-html在我的网站上放置一些HTML内容.问题是,如果内容具有链接,则单击链接会在同一窗口中打开.如何在新窗口中打开它?

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>

推荐答案

currentElement.content中包含的链接应具有属性target ='_ blank'

links contained in your currentElement.content should have the attribute target='_blank'

<a href="open/me/in/new/window" target="_blank">MyLink</a>

如果html内容来自外部来源,则可以添加一个过滤器来解析html内容,并将target属性添加到链接中

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

这是草图:

return angular.element(htmlContent).find('a').attr('target', '_blank');

更多细节

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

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

这篇关于ng-bind-html-如何在新窗口中打开链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆