Created
April 19, 2017 21:01
-
-
Save arbo77/25aadbba79da2d3b6e7292513beb00ad to your computer and use it in GitHub Desktop.
AngularJS contentditable directive
This file contains 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
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