Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs ckeditor directive sometimes fails to load data from a service

I used Vojta's angularJS directive but sometimes ckeditor would fail to display the data from a service. This almost never happened on a refresh, but often happened when navigating back to the page. I was able to verify that the $render function was always calling ck.setData with the correct data, but sometimes it would not display.

like image 432
Roma Avatar asked Mar 18 '13 17:03

Roma


1 Answers

It appears that the $render method was sometimes called before ckeditor was ready. I was able to resolve this by adding a listener to the instanceReady event to make sure that it was called at least once after ckeditor was ready.

  ck.on('instanceReady', function() {
    ck.setData(ngModel.$viewValue);
  });

In the interest of completeness, here is the complete directive that I used.

//Directive to work with the ckeditor
//See http://stackoverflow.com/questions/11997246/bind-ckeditor-value-to-model-text-in-angularjs-and-rails
app.directive('ckEditor', function() {
  return {
    require: '?ngModel',
    link: function(scope, elm, attr, ngModel) {
      var ck = CKEDITOR.replace(elm[0],
            {
                toolbar_Full:
                [
                { name: 'document', items : [] },
                { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
                { name: 'editing', items : [ 'Find','Replace','-','SpellChecker', 'Scayt' ] },
                { name: 'forms', items : [] },
                { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript' ] },
                { name: 'paragraph', items : [
                'NumberedList','BulletedList','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ] },
                { name: 'links', items : [] },
                { name: 'insert', items : [ 'SpecialChar' ] },
                '/',
                { name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
                { name: 'colors', items : [] },
                { name: 'tools', items : [ 'Maximize' ] }
                ]
                ,
                height: '290px',
                width: '99%'
            }
    );

      if (!ngModel) return;

      //loaded didn't seem to work, but instanceReady did
      //I added this because sometimes $render would call setData before the ckeditor was ready
      ck.on('instanceReady', function() {
        ck.setData(ngModel.$viewValue);
      });

      ck.on('pasteState', function() {
        scope.$apply(function() {
          ngModel.$setViewValue(ck.getData());
        });
      });

      ngModel.$render = function(value) {
        ck.setData(ngModel.$viewValue);
      };

    }
  };
});
like image 160
Roma Avatar answered Oct 14 '22 20:10

Roma