document.execCommand在angularJS中不起作用 [英] document.execCommand doesn't work in angularJS
问题描述
我有一个要在其中进行编辑的应用程序,就像StackOverflow上的这个一样.我不想使用textAngular指令,因为它太难理解了,所以我发现了这个Javascript函数document.execCommand,这似乎正是我所需要的.
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.
问题是我无法使其在AngularJs中工作.它没有给出任何错误,它什么也没做.
The problem is that I can't make it work in AngularJs. It's not giving any error, it just doesn't do anything.
我有一个内容可编辑的div:
I have a content editable div:
<div contenteditable id="text"><h5>Select a part of this text!</h5></div>
一个粗体按钮:
<i class="fa fa-bold" ng-click="wrapBold()"></i>
和功能:
$scope.wrapBold = function() {
document.execCommand('bold', false, null);
};
我尝试用$document
注入到控制器中,但随后却出现错误提示
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
推荐答案
textAngular实际上在内部使用document.execCommand(我是维护者FYI).
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.
从内存中,您必须做两件事;使其具有ng-click的元素具有属性unselectable="on"
,并且还可以捕获并阻止同一元素上的mousedown事件.这是我们在textAngular中设置按钮的方式: https://github.com/textAngular/textAngular/blob/ff8e48087f780d30f54e77b06f09e0b85f9517e9/src/taBind.js#L26-L39
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
$ document的问题在于,您需要使用$ document [0]来获取实际的HTML DOM元素,以便能够调用execCommand.
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.execCommand在angularJS中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!