CKEditor directive in AngularJS does not properly enforce the maxlength attribute in textarea

I am currently working on an AngularJS application with the CKEditor plugin. I have created a directive for CKEditor and everything seems to be functioning properly. However, I am facing an issue where I need to limit the character length to 50. I tried using maxlength="50", but it doesn't seem to work.

If anyone has a solution or workaround for this issue, please share it with me.

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 №1

To ensure proper functionality, it is important to assign an id to your textarea, like so:

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

You also need to manage 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));
        }
    } );
};

While this approach works effectively, do note that the content may include HTML tags that you may wish to retain.

Answer №2

Dealing with a similar issue, I devised a function that works seamlessly with CKEditor to emulate the functionality of the maxlength feature.

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 ensures that the input does not exceed the specified character limit.

If the limit is reached, it will return false, preventing any further inputs into the field.

However, pressing backspace or delete keys will still be allowed, enabling users to edit their content even at the character limit.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

Creating an href link within a button that is contained within a collapse component

I am grappling with an issue where my collapsed model is displaying more information about clients; however, when I click on the button inside it, instead of getting the specific client's data, I end up retrieving information for all clients. <ion ...

Mastering the use of useMasterKey in Parse with Node.js: A guide

Greetings everyone, I have developed my app using parse.com but now I need to utilize the master key as some users have administrative roles. Initially, I attempted to use the JS SDK but was advised to switch to Cloud Code. So, I tried using Express and ...

How can I design an SVG page similar to Coin360 and Market Maps?

I need to design a homepage similar to coin360.com, where I can display market maps and cryptocurrency rates. This page will be created using SVG elements for the answers section. Is there a pre-made template available for this design, or can someone gui ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

Gulp encountered an issue - TypeError: When attempting to call the 'match' method, it was found to be undefined

Currently, I'm attempting to utilize Gulp alongside BrowserSync for a website that is being hosted on MAMP and proxied through localhost:8888. Unfortunately, upon running gulp, I encounter the following error: [17:38:48] Starting 'browser-sync& ...

How can you efficiently identify and resolve coding errors or typos in your code?

While practicing node.js and express.js, I encountered an issue with finding typos. One such instance was when I mistakenly typed: const decoded = jwt.veryfy(token, config.get('jwtSecret')); instead of jwt.verify. Even though I eventually disc ...

The Bootstrap nav-tab functions perfectly on a local server, but unfortunately does not work when hosted remotely

UPDATE: Issue resolved so I have removed the Github link. It turns out that Github pages require a secure https connection for all linked scripts. Always remember to check the console! I encountered an unusual bug where the Bootstrap nav-tab functionality ...

Setting a radio button dynamically based on JSON data by using a select dropdown option

I am looking to generate questions from a pre-selected list using Vue.js. I have successfully implemented this with a radio button that reveals a new set of questions once checked. Now, I want to achieve the same functionality using a dropdown selection. ...

sole active component present

In my redux store, I have an array called rooms that is fetched from the server. In my component, I fetch this array from the store, map it, and display elements with the value of room['foo']. However, I am facing a problem where when a user clic ...

Associate a unique identifier string with a randomly generated integer identifier by Agora

For my current web project, I am utilizing a String username as the UID to connect to the channel in an Agora video call. However, I now need to incorporate individual cloud recording by Agora into the project. The challenge lies in the fact that cloud r ...

Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering: 1) I am having difficulty displaying the text sent from my controller onto my view... ...

Utilize Moment to round a date either up or down

I am using Moment to compare two datetime values. Specifically, I am utilizing Moment.isSameOrBefore function. However, my two date values are slightly different due to milliseconds. I want these two values to be considered the same: var date1 = ' ...

The Art of jQuery Data Processing

I'm currently working on extracting data from a form submission. Below is the code I've been using. function handleSubmission() { $("#questionForm").submit(function() { $.post("SubmitQuestion.php", $("#questionForm").serialize()).done(functi ...

MUI: Interaction with a button inside a MenuItem when not interacted with MenuItem itself?

Currently, I am utilizing MUI's Menu / MenuItem to create a menu of missions / tasks similar to the screenshot below: The MenuItem is interactive: // ... other code <MenuItem value={mission.issueIdentifierId} sx={{px: ...

Scrolling automatically

I'm experimenting with creating a typing effect using JavaScript and the typed.js library, found here: My approach involves using a div as a container. However, I've encountered an issue - when the text reaches the height of the div, scroll bars ...

Changing the order of element names depending on their location within the parent element using jQuery

<div class="content"> <div> <input type="text" name="newname[name]0"/> <div> <input type="text" name="newname[utility]0"/> <div> <textarea name="newname[text]0 ...

Make the most of your Bootstrap 3 layout by utilizing a full page container that fills both the width and height between a fixed header and

I am currently working on a basic bootstrap page with the Example template from Bootstrap's website. I want the content in the middle to take up the space between the header and footer, while ensuring that both the header and footer remain visible at ...

What are the steps to showcase a webcam stream in GLSL by leveraging Three.js?

One method of displaying a webcam video using ThreeJS involves creating a video texture, as shown below: video = document.getElementById( 'video' ); const texture = new THREE.VideoTexture( video ); texture.colorSpace = THREE.SRGBColorSpace; const ...

Employing an assortment of data points within a manufacturing facility

Currently, I have a factory that utilizes a JSON file wrapped in a $http.get request for testing purposes. However, this approach is not suitable when working within a SharePoint environment where JSON files are restricted. In the end, the goal is to integ ...