AngularJS: Inline edit
inline editing in a form with angularJS
by yahyaKACEM
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">
<h3>AngularJS: Inline Editing Example </h3>
<table ng-app="myApp">
<thead>
<tr>
<th>Customer Name: </th>
</tr>
</thead>
<tbody>
<tr>
<td><div contentEditable="true" ng-model="fName">John</div></td>
<td><i class="icon-edit"></i></td>
<tr>
<td>
<div contentEditable="true" ng-model="lName">Smith</div>
</td>
<td><i class="icon-edit"></i></td>
</tr>
</tbody>
</table>
<label>Click the text you wish you edit</label>
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
var myApp = 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('keydown', function(event) {
console.log("keydown " + event.which);
var esc = event.which == 27,
el = event.target;
if (esc) {
console.log("esc");
ctrl.$setViewValue(elm.html());
el.blur();
event.preventDefault();
}
});
}
};
});