document.execCommand doesn't work in angularJS

纵饮孤独 提交于 2019-12-10 10:43:33

问题


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 

回答1:


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.



来源:https://stackoverflow.com/questions/28781241/document-execcommand-doesnt-work-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!