Skip to content

Instantly share code, notes, and snippets.

@arbo77
Created April 19, 2017 21:01
Show Gist options
  • Save arbo77/25aadbba79da2d3b6e7292513beb00ad to your computer and use it in GitHub Desktop.
Save arbo77/25aadbba79da2d3b6e7292513beb00ad to your computer and use it in GitHub Desktop.
AngularJS contentditable directive
app.directive('edit', function() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
state: '=state',
},
link: function(scope, element, attrs, ngModel) {
function read() {
ngModel.$setViewValue(element.text());
}
ngModel.$render = function() {
element.html(ngModel.$viewValue.replace('\\n','<br>') || '');
};
scope.$watch('state', function(val) {
element.attr('contenteditable',val);
});
element.bind('blur keyup change', function(e) {
scope.$apply(read);
});
element.on('keydown', function (event){
if(element[0].attributes['multiline'] == undefined){
if(event.which == '13'){
window.event.cancelBubble = true;
event.returnValue = false;
}
}
});
}
};
});
// how to use
<span edit state="state.bio" ng-model="user.bio.data.name"></span>
// for multiline (replacement of textarea)
<span edit state="state.bio" ng-model="user.bio.data.address"></span>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment