Angular: WYSIWYG Widget TinyMCE - 1.0.0 (working)

An example of how to properly integrate a WYSIWYG like TinyMCE into AngularJS

by programmieraffe

HTML

<script src="http://resources.holycrap.ws/jscripts/tiny_mce/jquery.tinymce.js"></script>
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js" ng:autobind></script>
<div ng:app="myApp">
<div ng:controller="Tester">
        <div class="boxes">
            <div ng:repeat="box in boxes">
                <h1>{{box.name}}</h1>
                <textarea ui:tinymce ng:model="box.content"></textarea>
                Content in normal textbox (additional binding):<br /> <textarea ng:model="box.content"></textarea>
            </div>
        </div>
        <h1>boxes-data:</h1>        
        <pre>{{boxes}}</pre>
</div>

CSS

h1 { margin: 10px 0 4px; font-weight: bold; }
h2 { color: red; }
p { font-size: 80%; }
body { font-family: helvetica }
.boxes { margin-right: 10px; }
.clear { overflow: auto; }

JavaScript

var myApp = angular.module('myApp', []);

// thanks to:
// https://groups.google.com/forum/?fromgroups#!searchin/angular/directive$20model/angular/odcpnPa0R2k/r48ov-D2YFgJ
// https://groups.google.com/forum/?fromgroups#!searchin/angular/scope$20ngmodel/angular/WDEsUD5eYck/TLv3XXmv-ZcJ
// --- Custom TinyMCE Service --- //
myApp.directive('uiTinymce', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            
            element.tinymce({
                // Location of TinyMCE script
                script_url: 'http://resources.holycrap.ws/jscripts/tiny_mce/tiny_mce.js',

                // General options
                theme: "simple",

                // Change from local directive scope -> "parent" scope
                // Update Textarea and Trigger change event
                // you can also use handle_event_callback which fires more often
                onchange_callback: function(e) {

                    if (this.isDirty()) {
                        this.save();

                        // tinymce inserts the value back to the textarea element, so we get the val from element (work's only for textareas)
                        ngModel.$setViewValue(element.val());
                        scope.$apply();
                        
                        return true;
                    }
                }
            });

        }
    }
});


function Tester($scope) {
    $scope.boxes = [{
        name: 'First'},
    {
        name: 'Second'}];
}