AngularJS Contenteditable

by Warwick Grigg

HTML

<div ng-app="directive">
  <div contentEditable="true" ng-model="content">Edit Me</div>
  <pre>model = {{content}}</pre>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
<style>
​.ng-invalid { border: 1px solid red; }​
div[contentEditable] {
  cursor: pointer;
  background-color: #D0D0D0;
  margin-bottom: 1em;
  padding: 1em;
}

JavaScript

angular.module('directive', []).directive('contenteditable', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      // view -> model
      elm.bind('blur', function() {
        scope.$apply(function() {
          ctrl.$setViewValue(elm.html());
        });
      });

      // model -> view
      ctrl.$render = function(value) {
        elm.html(value);
      };

      // load init value from DOM
      ctrl.$setViewValue(elm.html());
    }
  };
});