2
\$\begingroup\$

I needed a simple way to add this test to certain click events:

if isUser then fireClickEvent else openSignInModal

So I made this directive:

angular.module 'openLETS.core.lib.guestLock', []
.directive 'authGuestLock', ($compile, $state, olString, Auth) ->

  ######### Private #########
  restrict = 'A'
  priority = 1
  terminal = true

  link = (scope, elem, attrs) ->
    $compile(elem.contents())(scope) # Terminal breaks translate, this is a workaround
    elem.on 'click', (e) ->
      e.preventDefault()
      e.stopPropagation()
      if scope.currentUser
        if attrs.ngClick then scope.$eval attrs.ngClick
        if attrs.uiSref
          params = scope.$eval olString.objFrom attrs.uiSref
          state = olString.until attrs.uiSref, '('
          $state.go state, params
      else
        Auth.openModal 'signUp'


  ######### Config #########
  restrict: restrict
  link: link
  priority: priority
  terminal: terminal

What do you think of it's readability and functionality?

This can be made generic quite easily by passing the condition and fallback expressions to the directive:

angular.module 'openLETS.core.lib.clickInterceptor', []
.directive 'clickInterceptor', ($compile, $state, olString, Auth) ->

  ######### Private #########
  restrict = 'A'
  priority = 1
  terminal = true
  scope    = 
    condition: '='
    fallback: '&'

  link = (scope, elem, attrs) ->
    $compile(elem.contents())(scope) # Terminal breaks translate, this is a workaround
    elem.on 'click', (e) ->
      e.preventDefault()
      e.stopPropagation()
      if attrs.condition
        if attrs.ngClick then scope.$eval attrs.ngClick
        if attrs.uiSref
          params = scope.$eval olString.objFrom attrs.uiSref
          state = olString.until attrs.uiSref, '('
          $state.go state, params
      else
        scope.fallback()


  ######### Config #########
  restrict: restrict
  priority: priority
  terminal: terminal
  scope: scope
  link: link
\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.