JSFiddle - React, Tailwind, and code Playground
by djkojb
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.4.0/ui-bootstrap.js"></script>
<div ng-controller="myCtrl">
<h4 editable model="name">name</h4>
<input text ng-model="name"/>
{{name}}
</div>
JavaScript
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
var editableDirective = angular.module('editable', ['ui.bootstrap.position']);
editableDirective.directive('editable', ['$compile','$position', function($compile, $position){
return {
restrict: 'A',
scope: {
'model':'='
},
template: "<span ng-click='edit()' ng-bind-html-unsafe='model|newlines'></span><textarea ng-model='model' ng-show='editing' ng-style='style' ng-blur='done()'></textarea>",
link: function(scope, element){
scope.editing = false;
scope.multiline = false;
var fixedStyle;
scope.edit = function(){
fixedStyle = getFixedStyle(element.find('span'));
scope.editing = true;
scope.multiline = isMultiline();
var pos = $position.position(element.find('span'));
var style = {
width: pos.width + "px",
height: pos.height + "px",
position: 'absolute',
left: pos.left + "px",
'top': pos.top + "px"
}
angular.extend(style, fixedStyle)
scope.style = style;
setTimeout(function(){
element.find('textarea')[0].focus();
},20);
}
function isMultiline(){
var lineHeight = getStyle(element.find('span')[0], 'line-height');
var spanHeight = getStyle(element.find('span')[0], 'height');
return parseInt(spanHeight,10) >= 2*parseInt(lineHeight,10);
}
function getFixedStyle(el){
return {
margin: getStyle(el[0], 'margin'),
padding: getStyle(el[0], 'padding'),
font: getStyle(el[0], 'font'),
}
}
function getDimStyles(el){
var width = el.prop('offsetWidth');
var height = el.prop('offsetHeight');
return {
width: width + 'px',
height: height + 'px'
...