【问题标题】:document.execCommand doesn't work in angularJSdocument.execCommand 在 angularJS 中不起作用
【发布时间】:2018-04-12 09:06:31
【问题描述】:

我有一个应用程序,我想在其中创建一个编辑区域,就像 StackOverflow 上的这个一样。我不想使用 textAngular 指令,因为它太难理解了,所以我找到了这个 Javascript 函数 document.execCommand,它似乎正是我所需要的。

问题是我不能让它在 AngularJs 中工作。它没有给出任何错误,它什么也没做。

我有一个内容可编辑的 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,我将它注入控制器,但它给了我一个错误提示

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

【问题讨论】:

  • 但似乎document.execCommand 是仅Mozilla 的API
  • 意味着它不适用于 Angular?
  • 你有这方面的 plunker/fiddle 吗?
  • @Adel 谁知道呢,但如果你发现 更容易 使用 Firefox 可用的 API 而不是其他主流浏览器..

标签: javascript angularjs document


【解决方案1】:

textAngular 实际上在内部使用 document.execCommand(我是维护者,仅供参考)。

您的代码非常正确,您面临的问题是,当您单击该按钮时,您会失去可内容编辑区域的焦点/选择,因此无法插入它。

凭记忆你必须做两件事;使带有 ng-click 的元素具有属性 unselectable="on" 并且还捕获并防止同一元素上的 mousedown 事件。下面是我们在 textAngular 中设置按钮的方法:https://github.com/textAngular/textAngular/blob/ff8e48087f780d30f54e77b06f09e0b85f9517e9/src/taBind.js#L26-L39

$document 的问题在于您需要使用 $document[0] 来获取实际的 HTML DOM 元素才能调用 execCommand。

【讨论】:

猜你喜欢
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多