Last active
August 29, 2015 13:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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