2

I have an application where I want to make an editing area, just like this one on StackOverflow. I don't want to use the textAngular directive, because it's too hard to understand, so I found about this Javascript function, document.execCommand, which it seems to be exactly what I need.

The problem is that I can't make it work in AngularJs. It's not giving any error, it just doesn't do anything.

I have a content editable div:

<div contenteditable id="text"><h5>Select a part of this text!</h5></div> 

a Bold button:

<i class="fa fa-bold" ng-click="wrapBold()"></i>

and the function:

$scope.wrapBold = function() {
            document.execCommand('bold', false, null);
        };

I have tried with $document, which I injected in the controller, but then it gives me an error saying

 TypeError: undefined is not a function at Scope.$scope.wrapBold 
Adel
  • 129
  • 1
  • 3
  • 12

1 Answers1

4

textAngular actually uses document.execCommand internally (I'm the maintainer FYI).

Your code is pretty much correct, the problem you are facing is that when you click on that button you loose the focus/selection of the contenteditable area, so it has no where to insert it.

From memory you have to do two things; Make the element with the ng-click on it have the attribute unselectable="on" and also catch and prevent the mousedown event on the same element. Here's how we setup the buttons in textAngular: https://github.com/textAngular/textAngular/blob/ff8e48087f780d30f54e77b06f09e0b85f9517e9/src/taBind.js#L26-L39

The problem with $document is that you need to use $document[0] to get the actual HTML DOM element to be able to call execCommand.

Simeon Cheeseman
  • 1,748
  • 1
  • 13
  • 24
  • Thanks a lot for the clear explanation. I finally made it work! – Adel Mar 02 '15 at 08:15
  • The git hub link is no more valid. Can you please update the answer. Also, if possible can you help me with https://stackoverflow.com/questions/49773118/how-is-styling-being-applied-on-selected-characters-of-the-string-angularjs – User985614 Apr 11 '18 at 11:07