maxlength not working in textarea for ckeditor angularjs directive

Alex Man picture Alex Man · Dec 31, 2014 · Viewed 13.5k times · Source

I have created an application in angularjs with ckeditor plugin, I have created a directive for ckeditor, The application is working fine but the issue is that i need to set a max character length to be 50, so i put maxlength="50", but its not working,

Can anyone please tell me some solution for this

JSFiddle

html

<div data-ng-app="app" data-ng-controller="myCtrl">

<h3>CKEditor 4.2:</h3>
    <div ng-repeat="editor in ckEditors">
    <textarea data-ng-model="editor.value" maxlength="50" data-ck-editor></textarea>
    <br />
    </div>
    <button ng-click="addEditor()">New Editor</button>
</div>

script

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

app.directive('ckEditor', [function () {
    return {
        require: '?ngModel',
        link: function ($scope, elm, attr, ngModel) {

            var ck = CKEDITOR.replace(elm[0]);

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

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

function myCtrl($scope){
    $scope.ckEditors = [{value: ''}];
}

Answer

Lajos Arpad picture Lajos Arpad · Dec 31, 2014

You need to add an id to your textarea, like this:

<textarea data-ng-model="editor.value" maxlength="50" id="mytext" data-ck-editor></textarea>

You need to handle the key events for CKEDITOR:

window.onload = function() {
    CKEDITOR.instances.mytext.on( 'key', function() {
        var str = CKEDITOR.instances.mytext.getData();
        if (str.length > 50) {
            CKEDITOR.instances.mytext.setData(str.substring(0, 50));
        }
    } );
};

This works, however, note, that the content contains html tags as well, you might want to keep them,