CKEDITOR中的文本占位符(角度上下文)

时间:2015-04-23 13:15:21

标签: angularjs ckeditor

我对CKEDITOR API还不是很熟悉,现在我一直试图找到在CKEDITOR可编辑区域内创建占位符的方法。占位符的预期行为 - 在用户与它的交互中消失,允许编辑内容。

我知道已经有一个占位符插件(http://ckeditor.com/addon/placeholder),但它的行为并不是我想要的。

更具体地说,问题是:是否可以订阅CKEDITOR内部特定元素的某些事件?

在角度上下文中工作我能够在将html传递给CKEDITOR ng-model之前编译我的html

$scope.html = $compile('<div><span text-placeholder >Placeholder</span></div>')($scope).html();

但是我没有尝试在指令中设置点击事件:

.directive('textPlaceholder', [ function () {
    return {
        restrict: 'A',
        link: function ($scope, $element) {
            //THIS DOES NOT WORK UNFORTUNATELY
            $element.on('click', function () {
                console.log('clicked');
            })
        }
    }
}])

有什么想法吗?

UPDATE:目前我想出了实现简单插件的解决方案,然后在CKEDITOR配置中引用它:

(function () {
CKEDITOR.plugins.add('text-placeholder', {
    init: function (editor) {

        editor.on('key', function (evt) {
            var el = $(CKEDITOR.instances.editor1.getSelection().getNative().baseNode.parentElement);
            if (el.hasClass('text-placeholder')) {
                el.remove();
            }
        });

    }
});

})();

对我来说很难看。任何反馈都表示赞赏。

2 个答案:

答案 0 :(得分:2)

这似乎是最终解决方案:

CKEDITOR.plugins.add('text-placeholder', {
    init: function (editor) {
        editor.on('contentDom', function () {
            var editable = editor.editable();
            editable.attachListener(editable, 'click', function (event) {
                var $placeholder = $(event.data.$.target).closest('.text-placeholder');
                if ($placeholder.length > 0) {
                    var selection = editor.getSelection();
                    selection.selectElement(selection.getStartElement());
                }
            });
        });
    }
});

这将使用&#34; text-placeholder&#34;对元素进行选择。用户将其聚焦在可编辑区域内时的类

<强>更新 See example

答案 1 :(得分:2)

你激励我自己写一个,用上面的例子作为起点。在我的用例中,我想从编辑器上的属性 - 数据占位符 - 中获取占位符文本,并在编辑器中显示它。当编辑器获得焦点时,占位符文本将消失。当编辑器模糊时 - 如果没有输入用户内容 - 再次显示占位符文本。另外,我设置了一个data-placeholder-showing属性,以便我可以使用CSS将占位符文本设置为灰色。这是我的代码:

CKEDITOR.plugins.add('text-placeholder', {
  init: function (editor) {
    var placeholder = editor.element.getAttribute('data-placeholder');
    editor.on('contentDom', function () {
      if (placeholder) {
        editor.setData(placeholder);
        editor.element.setAttribute('data-placeholder-showing', true);
      }
    });
    editor.on('focus', function() {
      if (editor.getData() === placeholder) {
        editor.element.setAttribute('data-placeholder-showing', false);
        editor.setData('');
      }
    });
    editor.on('blur', function() {
      if (placeholder && editor.getData().length === 0) {
        editor.element.setAttribute('data-placeholder-showing', true);
        editor.setData(placeholder);
      }
    });
  }
});