0

I'm trying to make all of the links in a modal open in a new tab, and due to the constraints of using angular, manipulating the DOM isn't as easy as I had thought it would be. Is there a way to bind a click event to the links and then make that click event open a new tab?

I have something like this

w = angular.element($window)
w.bind 'click', (e) ->
  # if link clicked open link in new tab?    
123
  • 8,733
  • 14
  • 57
  • 99
  • I guess it's not the angular one who can make it happen. You can user `HTML` properties to fix this. Use `target="_blank"` in your anchor tag by default. All tags will open in new tab. – Vineet Aug 26 '16 at 14:30

2 Answers2

1

Can't you just use ng-click on every link?

<a href="#" ng-click="openLink('http://www.google.com')">Open link in new window</a>

And have something like this in your controller:

$scope.openLink = (link) ->
  window.open link
  return

Or using just html:

<a href="http://www.google.com" target="_blank">Open link in new window</a>
Dario
  • 6,152
  • 9
  • 39
  • 50
  • Just writing the same thing. Why reinvent the wheel? – illeb Aug 26 '16 at 14:43
  • Because then you are tying DOM to controller where every controller would have to have this method or rely on the scope inheritance to provide it and that usually indicates the need for a directive. I like the simple target='_blank' it's simple and works! – Tyrone Wilson Aug 26 '16 at 14:48
0

Basic rule is that if you are going to do anything with the DOM then you should have a directive and use normal JQuery in the link function

new-tab.directive.coffee

angular.module 'my.module'
  .directive 'newTab', ($window) ->
    restrict: 'A'
    link: (scope, element, attributes) ->
      element.on('click', (evt)->
        # Open link in new tab here
      )

Example Usage:

<a href='/your/link' new-tab>

You will likely have to do some "prevent default" stuff as well so that the link doesn't still go to the same page in the current window (now that I think about it).

You could also try just setting the _target='blank' property on any and all a nodes.

I haven't tested this

new-tab-a.directive.coffee

angular.module 'my.module'
  .directive 'a', -> #I doubt this is a good idea though using 'a' as a directive name.
    restrict: 'E'
    link: (scope, element, attributes) ->
      attributes.target = '_blank'
Tyrone Wilson
  • 4,328
  • 2
  • 31
  • 35