AngularJS: Inline edit

inline editing in a form with angularJS

by hyperthalamus

HTML

<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script src="https://raw.github.com/coreyti/showdown/master/compressed/showdown.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<div contentEditable="true" ng-model="fName">John</div>
<div contentEditable="true" ng-model="lName">Smith</div>

CSS

div[contentEditable] {
  cursor: pointer;
  background-color: white;
    padding: .2em;
}
div[contentEditable]:focus {
  cursor: pointer;
  background-color: #D0D0D0;
    border: 1px solid red;
  padding: .2em;
}

JavaScript

angular.module('myApp', []);


myApp.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());
    
     elm.bind('keypress', function(e) {
         alert('someone press esc');
         if (e.charCode === 27) scope.$apply(function() {
          ctrl.$setViewValue(elm.html());
         });
        });
    
    }
      
  };
});