Using ng-model with contenteditable

Using ng-model with contenteditable

The ng-model directive is glorious! That is, until you try to use it with contenteditable elements. You’d think it would just… work… but it doesn’t. Fortunately, there’s a way to stiff-arm your way through this problem; just pop the following directive into your application:

@myApp.directive 'contenteditable', ->
restrict: 'A' # match the 'contenteditable' attribute
require: '?ngModel' # gain access to the associated model
priority: 1 # apply this directive before others
link: (scope, element, attrs, ngModel) ->
# no model? no poblem...
return if not ngModel
# set the view according to the model
ngModel.$render = -> element.html(ngModel.$viewValue || '')
# set the model according to the view
changeModel = -> ngModel.$setViewValue(element.text())
# watch for changes
element.bind 'blur keyup change', -> scope.$apply(changeModel)

One thought on “Using ng-model with contenteditable

Leave a Reply

Your email address will not be published. Required fields are marked *