Skip to content

Instantly share code, notes, and snippets.

@ChaseFlorell
Forked from ajoslin/gist:2942067
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChaseFlorell/9650230 to your computer and use it in GitHub Desktop.
Save ChaseFlorell/9650230 to your computer and use it in GitHub Desktop.
'use strict';
/*
*usage: <markdown ng:model="box.content"></markdown>
*/
myApp.directive('markdown', function ($compile) {
var nextId = 0;
//Make converter only once to save a bit of load each time - thanks to ajoslin
var converter = new Markdown.Converter();
return {
require: 'ngModel',
replace: true,
restrict: 'E',
template: '<div class="pagedown-bootstrap-editor"></div>',
link: function(scope, iElement, iAttrs, ngModel) {
var editorUniqueId = nextId++;
var newElement = $compile(
'<div>' +
' <div class="wmd-panel">' +
' <div id="wmd-button-bar-' + editorUniqueId + '"></div>' +
' <textarea class="wmd-input form-control" rows="10" id="wmd-input-' + editorUniqueId + '"></textarea>' +
' </div>' +
' <div class="wmd-gap"></div>'+
' <div class="panel panel-default">' +
' <div class="panel-heading">' +
' <strong>' + iAttrs.id + ' Preview</strong>' +
' </div>' +
' <div id="wmd-preview-' + editorUniqueId + '" class="wmd-panel wmd-preview"></div>' +
' </div>' +
'</div>')(scope);
iElement.html(newElement);
var help = function() {
// TODO: add nice modal dialog
alert("Do you need help?");
};
var editor = new Markdown.Editor(converter, "-" + editorUniqueId, {
handler: help
});
editor.run();
var $wmdInput = $("#wmd-input-" + editorUniqueId);
$wmdInput.on('blur', function () {
var rawContent = $wmdInput.val();
scope.$apply(function () {
ngModel.$setViewValue(rawContent);
});
});
// parent scope -> local change
scope.$watch(iAttrs.ngModel, function (value, oldValue) {
// this does not really work, so we do it manually - what is the correct way?
// scope.textareaValue = value;
if (value !== undefined) {
/*scope.$apply(function(){
textareaValue = value;
editor.refreshPreview();
})*/
$wmdInput.val(value);
//console.log($wmdInput.html());
editor.refreshPreview(); // forces the editor to re-render the preview according to the contents of the input, e.g. after you have programmatically changed the input box content. This method is only available after editor.run() has been called.
}
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment