javascript – 如何在光标处将文本/ HTML插入编辑器

我正在使用textAngular 1.4.1,我无法弄清楚如何在当前光标位置的textAngular指令中插入文本.

我原以为这是一个简单的操作.

我有一个SELECT,其中包含要插入的选项列表.当他们按下“插入”按钮时,我希望将文本插入到光标处的HTML中.

在我的控制器中,我有这个代码

$scope.insertToHtml = function (newText) {
    var editor = textAngularManager.retrieveEditor('item_bodyHTML')
    $timeout(function(){
        editor.scope.displayElements.text.trigger('focus');
        rangy.getSelection().getRangeAt(0).insertNode(document.createTextNode(newText)) 
    }); 
}

HTML:

 <div text-angular id="item_bodyHTML" name="item_bodyHTML" placeholder="Body HTML" ng-required="true" data-ng-model="item.bodyHTML" ></div>

<select class="form-control" placeholder="Insert Field" data-ng-model="insertHTML" ng-options="o.code as o.name for o in optionsToInsert"></select>

<button class="btn btn-default" type="button" ng-click="insertToHtml(insertHTML)">Insert</button>

最佳答案 解决这个问题的一种方法是设置插件,这通常是通过在配置中设置装饰器并在操作方法中插入html来完成的.是的,我知道,只是插入HTML!

在这里阅读https://github.com/fraywing/textAngular/wiki/Customising-The-Toolbar

所以基本上这个想法是你有一个模块设置和textangular

var module=angular.module('my_app',['textAngular']);

你将设置一个配置

    module.config(function($provide){
    $provide.decorator('taOptions', ['taRegisterTool', '$delegate', function(taRegisterTool, taOptions){       
        taRegisterTool('insertMyHtml', {
              buttontext: 'insert my html',
            action: function (taRegisterTool, taOptions) {                
         this.$editor().wrapSelection('insertHtml', '<h1>Hello, world!</h1>');             
            }
        });
        taOptions.toolbar=['insertMyHtml'];
        return taOptions;
    }]);
});

这将创建一个名为’insertMyHtml’的按钮来完成工作.你可以触发它等

要插入文本(将自动创建html),请将操作方法​​更改为

 action: function (taRegisterTool, taOptions) {                
             insertTextAtCursor( '<h1>Hello, world!</h1>');             
                }

而且insertTextAtCursor是

 function insertTextAtCursor(text) {
                    var sel, range;
                    if (window.getSelection) {
                        sel = window.getSelection();
                        if (sel.getRangeAt && sel.rangeCount) {
                            range = sel.getRangeAt(0);
                            range.deleteContents();
                            range.insertNode(document.createTextNode(text));
                        }
                    } else if (document.selection && document.selection.createRange) {
                        document.selection.createRange().text = text;
                    }
                }

我直接从这个答案How to insert text/symbols from a custom button on textAngular toolbar得到了这个方法

希望这会给出一些想法

点赞