Skip to content

Instantly share code, notes, and snippets.

@mlegenhausen
Created August 7, 2013 18:00
Show Gist options
  • Save mlegenhausen/6176690 to your computer and use it in GitHub Desktop.
Save mlegenhausen/6176690 to your computer and use it in GitHub Desktop.
angular editor directive test
// Code goes here
angular.module('app', [])
.controller('AppCtrl', function($scope) {
$scope.content = '<p>Hallo Welt</p>';
})
.constant('KEY', {
'BACKSPACE': 8,
'ENTER': 13
})
.directive('ngEditor', function($document, KEY) {
return {
require: '^ngModel',
link: function(scope, element, attrs, controller) {
var $ = angular.element;
var $container = angular.element('<div class="editor"></div>');
var $cursor = angular.element('<span class="cursor blink">&nbsp;</span>');
var $dom;
var $current;
$container.bind('click', function(event) {
console.log(event);
$current = $(event.toElement);
$(event.target).append($cursor);
});
$document.bind('keydown', function(event) {
var text = $current.text();
console.log(event.keyCode);
switch (event.keyCode) {
case KEY.BACKSPACE:
if (text.length === 1) {
$next = $current.next() || $current.previous();
$current.remove();
$current = $next;
} else {
text = text.substr(0, text.length - 2);
}
break;
case KEY.ENTER:
var $paragraph = $('<p>');
$current.parent().append($paragraph);
$current = $paragraph;
break;
default:
var charCode = String.fromCharCode(event.keyCode);
if (event.shiftKey) {
charCode = charCode.toLowerCase();
}
text += charCode;
}
$current.text(text);
$current.append($cursor);
event.preventDefault();
});
scope.$watch(attrs.ngModel, function(content) {
$dom = $(content);
$container.append($dom);
});
element.after($container);
//element.css('display', 'none');
}
};
})
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment