Skip to content

Instantly share code, notes, and snippets.

@AlexandreBonneau
Created October 18, 2016 02:24
Show Gist options
  • Save AlexandreBonneau/94bdfe6164a7376f2247ab8af483c4c3 to your computer and use it in GitHub Desktop.
Save AlexandreBonneau/94bdfe6164a7376f2247ab8af483c4c3 to your computer and use it in GitHub Desktop.
Angular 1 directive that allows the user to cancel a text input change with 'Escape'
/**
* This directive allow the user to 'cancel' an input with the 'Esc' key.
* Basically this saves the input value on focus, and set it back to this 'old' value whenever the user hit 'Esc'.
* Additionally, if the input value did not change when the user hits 'Esc', then the whole input value is selected.
*
* @usage <element data-cdz-cancellable contenteditable></element>
*/
app.directive('cdzCancellable', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ngModelCtrl) {
if (attrs.type === 'radio' || attrs.type === 'checkbox') {
return;
}
var oldValue = null;
function saveCurrentElementValue() {
if (isCdzNumericNode(elm)) { //When used with the autoNumeric library
oldValue = elm.autoNumeric('get');
}
else {
oldValue = elm.val();
}
}
elm.bind('focus', function() { //On focus, save the initial value
scope.$apply(function() {
saveCurrentElementValue();
});
});
elm.bind('keyup', function(event) { //On 'Esc' key, set back the initial value
var key = (typeof event.which === "undefined")?event.keyCode:event.which;
if (key === cdzUtils.keyCode.Esc) {
event.preventDefault();
if ("" === oldValue) {
oldValue = 0;
}
ngModelCtrl.$setViewValue(oldValue);
scope.$apply(); //Launch a $digest
ngModelCtrl.$render();
this.select(); //Auto select the input text to facilitate its edition
scope.$broadcast('escapePressed');
}
});
var onEnterPressedOff = scope.$on('enterPressed', function(event) { //Important : update the saved value if the form is validated
saveCurrentElementValue();
});
scope.$on('$destroy', function() {
elm.unbind('focus');
elm.unbind('keyup');
onEnterPressedOff();
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment