简体   繁体   English

document.execCommand在angularJS中不起作用

[英]document.execCommand doesn't work in angularJS

I have an application where I want to make an editing area, just like this one on StackOverflow. 我有一个要在其中进行编辑的应用程序,就像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. 我不想使用textAngular指令,因为它太难理解了,所以我发现了这个Javascript函数document.execCommand,这似乎正是我所需要的。

The problem is that I can't make it work in AngularJs. 问题是我无法使其在AngularJs中工作。 It's not giving any error, it just doesn't do anything. 它没有给出任何错误,只是什么也没做。

I have a content editable div: 我有一个内容可编辑的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 我已经尝试了$document ,我注入了控制器,但是它给我一个错误,说

 TypeError: undefined is not a function at Scope.$scope.wrapBold 

textAngular actually uses document.execCommand internally (I'm the maintainer FYI). textAngular实际上在内部使用document.execCommand(我是维护者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. 您的代码几乎是正确的,您面临的问题是,当您单击该按钮时,您失去了对contenteditable区域的焦点/选择,因此它没有插入位置。

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. 使其具有ng-click的元素具有属性unselectable="on"并且还可以捕获并防止对同一元素进行mousedown事件。 Here's how we setup the buttons in textAngular: https://github.com/textAngular/textAngular/blob/ff8e48087f780d30f54e77b06f09e0b85f9517e9/src/taBind.js#L26-L39 这是我们在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. $ document的问题在于,您需要使用$ document [0]来获取实际的HTML DOM元素,才能调用execCommand。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM