Skip to content

Instantly share code, notes, and snippets.

@marisks
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marisks/9108486 to your computer and use it in GitHub Desktop.
Save marisks/9108486 to your computer and use it in GitHub Desktop.
AngularJS input text field with read mode as span and editing with double click.
// usage: <app-dbl-text ng-model="model.name"></app-dbl-text>
app.directive('appDblText', function ($compile, $parse) {
return {
restrict: 'E',
template: '<div><span></span><input type="text" ng-model="ngModel" class="form-control" style="display:none;"></div>',
replace: true,
link: function(scope, elem, attrs) {
var model = attrs.ngModel;
var spans = elem.find('span');
var inputs = elem.find('input');
var getter = $parse(model);
var setter = getter.assign;
scope.oldVal = null;
elem.on('dblclick', function() {
spans.hide();
inputs.show();
scope.oldVal = getter(scope);
console.log(scope.oldVal);
});
elem.find('input').on('blur', function() {
scope.oldVal = null;
spans.show();
inputs.hide();
});
var ESCAPE_KEY = 27;
elem.on('keydown', function(event) {
if (event.keyCode === ESCAPE_KEY) {
spans.show();
inputs.hide();
scope.$apply(function() {
setter(scope, scope.oldVal);
});
}
});
spans.text('{{' + model + '}}');
inputs.attr('ng-model', model);
return $compile(elem)(scope);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment