maxlength not working in textarea for ckeditor angularjs directive

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: ''}];
}

Answers:

Answer

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,

Answer

I came across this same issue. I made this function which works with CKEditor to basically mimic the maxlength function.

window.onload = function() {            
    CKEDITOR.instances.mytext.on('key',function(event){
        var deleteKey = 46;
        var backspaceKey = 8;
        var keyCode = event.data.keyCode;
        if (keyCode === deleteKey || keyCode === backspaceKey)
            return true;
        else
        {
            var textLimit = 50;
            var str = CKEDITOR.instances.mytext.getData();
            if (str.length >= textLimit)
                return false;
        }
    });    
};

This function will check to make sure the input does not have more than the allowed characters.

If it does it will return false which simply does not allow any more inputs into the field.

If the user presses backspace or delete then it will return true which still allows the user to change their content if they reach the content limit.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.