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

Experiencing difficulty with parsing an array's json/string version within an Angular controller

Updated question for clearer understanding! I'm currently working on an Angular-Rails application and facing challenges when it comes to parsing an array. One of my ActiveRecord models has an attribute that is an array. Before reaching my Angular app ...

Tips for dividing by a large number

I am currently attempting the following: const numerator = 268435456; const denominator = 2 ** 64; const decimalFraction = numerator / denominator; In order to achieve this, I have experimented with utilizing the code provided in this link: : const rawVal ...

Retrieve the keys of a JSON object from an unfamiliar JSON format

I have a challenge involving an algorithm where I need to extract all keys (including nested objects and arrays of objects) from a JSON file with unknown structures and store them in one array. { "key": "value to array", "key": [{ "key": { "k ...

Ionic ion-view missing title issue

I'm having trouble getting the Ionic title to display on my page: http://codepen.io/hawkphil/pen/oXqgrZ?editors=101 While my code isn't an exact match with the Ionic example, I don't want to complicate things by adding multiple layers of st ...

Editable content <div>: Cursor position begins prior to the placeholder

Having an issue with a contenteditable div where the placeholder text starts behind the cursor instead of at the cursor position. Any suggestions on how to correct this? <div id="input_box" contenteditable="true" autofocus="autofocus" autocomplete="o ...

Display the text from a function in an imported component using React

Attempting to break down HTML chunks into smaller pieces stored in the components folder. (Note: the HTML is actually written in JSX). The goal is to import the [Navigation] component and have it display its content. I am aware that there are tools avail ...

Swapping the source of a specific ng-include element when it is being hovered over, with the source value being a variable in

I have several ng-include elements with the src attribute set to $scope.template_url. I am trying to figure out how to change the src of only the hovered element to a new template, without affecting all the other elements. Any ideas on how I can achieve t ...

Utilize Javascript to load content dynamically while ensuring each page has a distinct link to individual content pages

As a newcomer to web development, I wanted to share my issue in hopes of finding a more efficient solution than what I've been attempting. Recently, I made changes to my website so that content is loaded dynamically using the jQuery load() function. T ...

The code is nearly identical except for one issue that causes an infinite loop within useEffect

Hey, I'm new to reactjs and I've encountered a puzzling situation with the following two code snippets. I can't figure out why using the "First code" results in an infinite loop (endless '123' log outs in my browser console) while ...

Avoid automatically scrolling to the top of the page when a link is clicked

Within my ASP.NET MVC 5 application, there exists a partial view containing the following code: <a href="#" onclick="resendCode()" class="btn btn-link btn-sm">Resend</a> Additionally, on the View, the resendCode() function is present: funct ...

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

Troubleshooting Jqgrid Keyboard Navigation Problem

Here is a link to the jsfiddle code snippet. Upon adding jQuery("#grid").jqGrid('sortableRows'); into my JavaScript code, I encountered an issue where keyboard navigation no longer worked after sorting rows Below is the JavaScript code snippet: ...

How can I access the ng-template in a component?

How can I reference <ng-template #modal_Template> in my component.ts file? Previously, I triggered a modal using a button on my HTML file and included this code: <button type="button" class="btn btn-primary" (click)="openModal(modal_Template)"> ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

The press of the Enter key does not trigger the button

I'm facing an issue with a form that has just one field for user input and a button that triggers some jQuery to hide the login form when clicked. However, pressing enter after entering text causes the page to refresh... I'm starting to think th ...

Utilizing AngularJS: Accessing the parent controller from a child component using the controllerAs syntax

Looking to access a function from the parent controller within my directive using the controllerAs notation in Angular 1.3.14. Here is the structure: Controller (with save function) (Child) controller Directive with a template (and isolated scope). Ins ...

Ways to stop click propagation in the case of a parent anchor link containing a button among its children

Every time I click on the Link parent, it triggers a click event on the button as well. I want these events to be independent. <Link className="product-item__link" to={`/products/${product.category}/${product.id}`} > <div className ...

What is the best way to activate a click event within an ng-repeat loop in AngularJS

Is there a way to trigger an event click handler in angular where clicking the button will also trigger the span element? I've tried using the nth-child selector without success. Any suggestions on how to achieve this? I also attempted to use jQuery s ...

Error alert: Blinking display, do not dismiss

I am trying to make it so that when the "enviar" button is clicked, the "resultado" goes from being hidden ("display:none") to being visible ("display:block"). This is my html document: <script type="text/javascript"> function showResu ...

Tips for eliminating the page URL when printing a page using window.print() in JavaScript or Angular 4

Can someone help me with a function that uses window.print() to print the current page, but I need to remove the page URL when printing? I'm looking to exclude the URL from being printed and here is the code snippet where I want to make this adjustme ...