Skip to content

Instantly share code, notes, and snippets.

@daniel-nelson
Created June 15, 2015 19:31
Show Gist options
  • Save daniel-nelson/6eff2a14157ec6576dc1 to your computer and use it in GitHub Desktop.
Save daniel-nelson/6eff2a14157ec6576dc1 to your computer and use it in GitHub Desktop.
Bootstrap popover based confirm directive for Angularjs
# Usage:
# <div "ng-repeat"="comment in comments">
# <a class="remove" href="" "pj-confirm"="Really remove?" "popover-placement"="left"
# "on-confirm"="deleteComment" "callback-argument"="comment" "confirm-btn-label"="Yes" "cancel-btn-label"="No">Delete</a>
# </div>
#
# Dependencies:
# jQuery UI (for position function)
# Bootstrap CSS
@pjModule ||= angular.module(
'PlateJoy',
[]
)
pjModule.directive 'pjConfirm', ->
restrict: 'A'
scope:
confirmMessage: '@pjConfirm'
onConfirm: '='
onCancel: '='
callbackArgument: '='
popoverPlacement: '@'
confirmBtnLabel: '@'
cancelBtnLabel: '@'
link: ($scope, el, attrs) ->
$confirm_el = null
hideConfirm = ->
$('body').off('click', hideConfirm)
$confirm_el.remove() if $confirm_el
$confirm_el = null
showConfirm = ->
hideConfirm()
$('body').on('click', hideConfirm)
confirm_template = """
<div class="confirm popover #{$scope.popoverPlacement}">
<div class="arrow"></div>
<div class="popover-inner">
<div class="popover-content">
#{$scope.confirmMessage}
<button class="btn btn-default btn-outline btn-xs ng-binding">#{$scope.cancelBtnLabel}</button>
<button class="btn btn-danger btn-outline btn-xs ng-binding">#{$scope.confirmBtnLabel}</button>
</div>
</div>
</div>
"""
$confirm_el = $(confirm_template)
confirm_button = $confirm_el.find('.btn-danger')
cancel_button = $confirm_el.find('.btn-default')
callConfirmCallback = ->
return unless $scope.onConfirm
if $scope.callbackArgument
$scope.onConfirm($scope.callbackArgument)
else
$scope.onConfirm()
$scope.$parent.$apply()
callCancelCallback = ->
return unless $scope.onCancel
$scope.onCancel()
$scope.$parent.$apply()
confirm_button.on 'click', ($event) ->
callConfirmCallback()
hideConfirm()
$event.stopPropagation()
cancel_button.on 'click', ($event) ->
callCancelCallback()
hideConfirm()
$event.stopPropagation()
$('body').append($confirm_el)
$confirm_el.position
my: 'right-10 center'
at: 'left center'
of: $(el)
_.defer ->
$confirm_el.addClass('fade in')
toggleConfirm = ($event) ->
if $confirm_el
hideConfirm()
else
showConfirm()
$event.stopPropagation()
$(el).on('click', toggleConfirm)
$scope.$on '$destroy', ->
hideConfirm()
$(el).off('click', toggleConfirm)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment