Skip to content Skip to sidebar Skip to footer

"execcommand" Is Not Working With Angularjs

In the process of creating my own mini/simplified text editor I ran into the issue of using execCommand. I do not know why my code isn't working. I tried to prevent the mousedown e

Solution 1:

execCommand applies to the current selection. When you click the button (in fact, anywhere outside your textinput), you unselect currently selected text. The purpose of this code is to restore the selection of your contentEditable. This is also true if there is currently nothing selected, then at least the caret position needs to be restored (which is a selection with a length of 0 characters).

First you need to store the selected ranges every time the user changed the selection (in my case, on keyup and mouseup):

this.textInput.onmouseup = this.textInput.onkeyup = function(){
    this.updateSelection();
    this.updateStatus();
}.bind(this);

Storing the selection ranges in an array for that purpose:

this.updateSelection = function(){
    this.selection = [];
    var sel = this.getSelection();
    for(var i=0; i<sel.rangeCount; i++)
        this.selection.push(sel.getRangeAt(i).cloneRange());
};

And before executing the command, restoring the selection:

this.reselect = function(){
    var sel = this.getSelection();
    sel.removeAllRanges();
    for(var i=0; i<this.selection.length; i++)
        sel.addRange(this.selection[i].cloneRange());
};

this.reselect();
document.execCommand("bold");

this.getSelection is defined as (although admittedly a little bit rude):

returnwindow.getSelection ? window.getSelection() : 
(document.getSelection ? document.getSelection() :
document.documentElement.getSelection() );

I assume you have a contentEditable, not just a simple textarea.

Post a Comment for ""execcommand" Is Not Working With Angularjs"