123 123 - 3 months ago 23
CoffeeScript Question

Bind click event to open a link in new tab

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?

Answer

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'