Question

I'm experiencing an issue trying to use tinymce API inside an angular directive in JSFiddle. Here is the example The tinymce editor is initialised just fine, there's no errors in browser console. But I get 'undefined' if I try to get an instance of the tinymce Editor. The question is: why does tinymce.get(id); result in undefined?

HTML:

<div ng-app="myApp">
    <div ng-controller="MainCtrl">
        <my-editor ng-model="text"></my-editor>
    </div>
</div>

JS:

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

app.controller('MainCtrl', function($scope) {

});
app.directive('myEditor', function () {
    var uniqueId = 0;
    return {
        restrict: 'E',
        require: 'ngModel',
        scope: true,
        template: '<textarea></textarea>',
        link: function (scope, element, attrs, ngModel) {
            var id = 'myEditor_' + uniqueId++;
            element.find('textarea').attr('id', id);
            tinymce.init({
                selector: '#' + id
            });

            var editor = tinymce.get(id);
            alert(editor); **// why is this undefined?**
        }
    }
});

I've also played with options in Frameworks & Extensions section of JSFiddle. But with no success.

Was it helpful?

Solution

You are dealing with the issue, where the elements have not been appended to the dom when you are doing your alert. (look at the html in firebug)

<my-editor ng-model="text" class="ng-scope ng-pristine ng-valid">
    <textarea id="myEditor_0"></textarea>
</my-editor>

Placing the alert inside of a setTimeout will allow you to alert() the object.

setTimeout(function(){
     var editor = tinymce.get(id);
     alert(editor); // why is this undefined?
},0);

OTHER TIPS

The proper way to go is to set the init_instance_callback option in tinyMCE.init or in tinymceOptions if you are using angular-ui-tinymce :

$scope.tinymceOptions = {
  init_instance_callback : function(editor) {
     MyCtrl.editor=editor
     console.log("Editor: " + editor.id + " is now initialized.");
     editor.on('Change', function(editor, e) {
        MyCtrl.func()
     });             
}

Additionally to the answer Mark gave:

You will need to wait for the editor to get initalized and ready to be usable. For this you may use the onInit tinymce handler. onInit gets fired when the editor is ready.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top