Skip to content

Instantly share code, notes, and snippets.

@Luxiyalu
Last active August 29, 2015 14:07
Show Gist options
  • Save Luxiyalu/eccc8c4f864e42f6d197 to your computer and use it in GitHub Desktop.
Save Luxiyalu/eccc8c4f864e42f6d197 to your computer and use it in GitHub Desktop.
AngularJS: Click Outside of Directory
app.controller 'AppCtrl', ($rootScope) ->
# broadcast click event within AppCtrl
$(document).on 'click', (e) ->
$rootScope.$broadcast 'click', e.target
# this target is a js dom element
app.directive 'dropdownBox', ($rootScope) ->
scope: {}
link: (scope, element, attr) ->
# listen to click event, within a link function:
offEvent = $rootScope.$on 'click', (e, target) ->
if !element.find($(target)).length # clicked outside of directory
# equivalent to: !($.contains(element[0], target) || element.is(target))
scope.showDropdown = false
scope.$apply()
# don't forget to apply! since angular has already digested the whole click
# before jquery's event, without $apply it wouldn't be applied at this point
# don't forget to turn off the event when scope is destroyed
$scope.$on '$destroy', -> do offEvent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment