Skip to content

Instantly share code, notes, and snippets.

@itsmelion
Created December 11, 2017 13:00
Show Gist options
  • Save itsmelion/d731990ce27e2230d07d5ec737a0fd70 to your computer and use it in GitHub Desktop.
Save itsmelion/d731990ce27e2230d07d5ec737a0fd70 to your computer and use it in GitHub Desktop.
Click'n Edit Directive
app.directive('editable', ['$compile', '$parse', function ($compile, $parse) {
return {
restrict: 'AE',
link: function (scope, element, attrs) {
var isEditing = false;
element.bind('click', elemClick);
element.addClass('editable-field');
function elemClick() {
if (isEditing) {
return;
}
isEditing = true;
element.hide();
if (!attrs.ngOpt) {
$compile('<input type="text" value="' + element.html() + '" style="width: 100%;" />')(scope).insertAfter(element);
input = element.next('input');
input.focus().select();
input.bind('blur keyup', elemOut);
input.addClass('editable-input');
}
};
function elemOut(event) {
if (event.type === "blur" || event.keyCode === 13) {
if (element.html() !== input.val()) {
saveField();
} else {
cancelField();
}
} else if (event.keyCode === 27) {
cancelField();
}
};
function cancelSelect() {
isEditing = false;
select.remove();
element.show();
}
function cancelField() {
isEditing = false;
input.remove();
element.show();
};
function saveField() {
var text = input.val();
scope.$apply(function () {
if (attrs.ngBind != undefined && attrs.ngBind != '') {
$parse(attrs.ngBind).assign(scope, text);
}
});
cancelField();
if (attrs.ngEvent) {
scope.$emit('edit-in-place:' + attrs.ngEvent);
} else {
scope.$emit('edit-in-place:changed');
}
};
// Adjustment for Safari Browser
scope.$watch(attrs.ngBind, function (n, o) {
if (!isEditing && n) {
element[0].style.display = "inline-block";
}
});
},
};
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment