Skip to content

Instantly share code, notes, and snippets.

@lyschoening
Last active August 29, 2015 14:06
Show Gist options
  • Save lyschoening/4d3b911d12707a5e7526 to your computer and use it in GitHub Desktop.
Save lyschoening/4d3b911d12707a5e7526 to your computer and use it in GitHub Desktop.
AngularJS directive for a two-click confirm button that resets state when it loses focus and can only be clicked once
<confirm-button confirm-text="Are you sure?">Delete Item</confirm-button>
<confirm-button confirm-icon="fa-trash" confirm-text="Confirm">Delete Item</confirm-button>
angular.module('ngConfirm', [])
.directive('confirmButton', function ($parse) {
return {
template: '<button ng-blur="cancel()" ng-click="step()" ng-disabled="confirmed" ng-class="{\'btn-danger\': activated, disabled: confirmed}">' +
'<span ng-if="!activated" ng-transclude></span>' +
'<span ng-if="activated">' +
'<i ng-if="confirmIcon" class="fa {{confirmIcon}}"></i> ' +
'{{ confirmText }}</span>' +
'</button>',
restrict: 'E',
replace: true,
transclude: true,
scope: true,
link: function(scope, element, attrs) {
scope.activated = false;
scope.confirmed = false;
scope.confirmText = attrs.confirmText;
scope.confirmIcon = attrs.confirmIcon;
scope.step = (event) => {
if(!scope.activated) {
scope.activated = true;
} else if(!scope.confirmed) {
scope.activated = false;
scope.confirmed = true;
$parse(attrs.confirm)(scope, {});
}
};
scope.cancel = () => {
if(!scope.confirmed) {
scope.activated = false;
scope.confirmed = false;
}
};
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment