Search code examples
angularjsangularjs-directiveangularjs-ng-repeatckeditor4.x

How to get instances of ckeditor with ng-repeat?


I am trying to use ckeditor with angularjs I have added a directive for the same. It is working fine. The problem is when I try to get the instances list of the ckeditor.

// directive

app.directive('ckeditor', function () {
     return {
        require: '?ngModel',
        link: function (scope, element, attr, ngModel) {
            var ck = CKEDITOR.replace(element[0]);
            if(!ngModel)return;
            ck.on('pasteState', function () {
                scope.$apply(function () {
                    ngModel.$setViewValue(ck.getData());
                });
            });
            ngModel.$render = function (value) {
                ck.setData(ngModel.$viewValue);
            };
        }
    };
});

// ng-repeat

<div ng-repeat="key in []| range:0:(vm.listCount-1)"> 
     <textarea ckeditor id="content_{{key + 1}}"
               ng-model="vm.contentList[key].content">
     </textarea>
</div>

In controller I am trying to get instances list. There instead of content_0,content_1 etc. I am getting content_{{key + 1}} only one instance

console.log(CKEDITOR.instances);

I want to get the proper instance of the ckeditor but I am getting only one value that is content_{{key + 1}} Please someone suggest.


Solution

  • My guess is that the directive needs to set the id attribute before invoking CKEDITOR.replace:

    app.directive('ckeditor', function () {
         return {
            require: '?ngModel',
            link: function (scope, element, attr, ngModel) {
                //COMPUTE id attribute
                if (attr.key) {
                    var keyValue = scope.$eval(attr.key);
                    element[0].id += "_"+keyValue;
                };
                var ck = CKEDITOR.replace(element[0]);
                if(!ngModel)return;
                ck.on('pasteState', function () {
                    scope.$apply(function () {
                        ngModel.$setViewValue(ck.getData());
                    });
                });
                ngModel.$render = function (value) {
                    ck.setData(ngModel.$viewValue);
                };
            }
        };
    });
    

    Usage:

    <div ng-repeat="key in [0,1]"> 
         <textarea ckeditor key="$index+1" id="content"
                   ng-model="vm.contentList[key].content">
         </textarea>
    </div>
    

    The CKEDITOR is likely instantiating the editor before the AngularJS framework computes id="content_{{key + 1}}".