Skip to content

Instantly share code, notes, and snippets.

@mlynch
Last active August 29, 2015 14:08
Show Gist options
  • Save mlynch/e0098e2bb8fe3b622014 to your computer and use it in GitHub Desktop.
Save mlynch/e0098e2bb8fe3b622014 to your computer and use it in GitHub Desktop.
angular.module('maxlynch')
/**
* A simple ace-editor widget for adding a rich code editor
* in place of a textarea with full ngModel support.
*
* Usage:
*
* <ace-editor language="javascript" theme="monokai"></ace-editor>
*
* Make sure to set the height of the ace-editor to the size you want.
*/
.directive('aceEditor', [function() {
return {
restrict: 'E',
require: '?ngModel',
template: '<div class="editor" style="width: 100%; height: 100%"></div>',
link: function($scope, $element, $attr, ngModel) {
var editor = ace.edit($element[0].querySelector('.editor'));
editor.setTheme('ace/theme/' + ($attr.theme || 'chrome'));
editor.getSession().setMode('ace/mode/' + $attr.language);
editor.getSession().setUseWrapMode(true);
editor.setShowPrintMargin(false);
editor.on('change', function(e) {
ngModel.$setViewValue(editor.getValue());
});
// Set the value twice to avoid ace selecting the content. (A hack, I know)
ngModel.$render = function() {
editor.setValue(ngModel.$viewValue, -1);
editor.setValue(ngModel.$viewValue, 1);
};
$element.on('$destroy', function() {
editor.destroy();
});
}
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment