表情符号支持textarea或contenteditable div

时间:2015-10-16 13:30:12

标签: angularjs contenteditable emoticons

尝试使用表情符号实现textarea组件,并在写入时支持

我希望能够在div上展示过滤/生成的html结果(带有角度表情符号过滤器)时备份原始文本(仅限ascii chars)。

我最初的解决方案是

<textarea ng-model="text" ng-change="..." ng-focus="..."></textarea>
<div ng-bind-html="text | myEmoticonsFilter"></div>

但是我无法使用隐藏的textarea。此外,有了这个,我将无法鼠标选择文本并删除或复制/粘贴安全。

我还考虑使用<div contenteditable="true">,但ng-focusng-change将无法处理。

有没有人对如何继续这个有任何兴趣?

编辑1 :这是jsfiddle,尝试我正在做的事情。到目前为止,能够替换第一次出现,但行为仍然不稳定。我正在使用contenteditable指令进行双向数据绑定并过滤表情符号模式。

编辑2 :关于我的陈述,即ng-focusng-change无法处理,这是不正确的 - ng-focus本身可以<div contenteditable="true">工作只要使用ng-change声明指令并设置相应的ngModel$modelValue({{3}中提供了示例),1}}和$viewValue就会起作用在编辑1 )。

1 个答案:

答案 0 :(得分:5)

以一致的跨浏览器方式执行此操作的唯一方法是使用将表情符号转换为图像的WYSIWYG字段。

有一个jQuery插件jquery-emojiarea可以满足您的需求,因此您只需要创建一个包含此插件的指令,然后您即可参加比赛。由于它使用表情符号语法:smile:输入隐藏的textarea,因此angular应该没有任何难度。

这是我一起工作的指令。 http://jsfiddle.net/dboskovic/g8x8xs2t/

var app = angular.module('app', []);
app.controller('BaseController', function ($scope) {
    $scope.text = 'This is pretty awesome. :smile: :laughing:';
});
app.directive('emojiInput', function ($timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, $el, $attr, ngModel) {
            $.emojiarea.path = 'https://s3-us-west-1.amazonaws.com/dboskovic/jquery-emojiarea-master/packs/basic';
            $.emojiarea.icons = {
                ':smile:': 'smile.png',
                ':angry:': 'angry.png',
                ':flushed:': 'flushed.png',
                ':neckbeard:': 'neckbeard.png',
                 ':laughing:': 'laughing.png'
            };
            var options = $scope.$eval($attr.emojiInput);
            var $wysiwyg = $($el[0]).emojiarea(options);
            $wysiwyg.on('change', function () {
                ngModel.$setViewValue($wysiwyg.val());
                $scope.$apply();
            });
            ngModel.$formatters.push(function (data) {
                // emojiarea doesn't have a proper destroy :( so we have to remove and rebuild
                $wysiwyg.siblings('.emoji-wysiwyg-editor, .emoji-button').remove();
                $timeout(function () {
                    $wysiwyg.emojiarea(options);
                }, 0);
                return data;
            });
        }
    };
});

用法:

<textarea ng-model="text" emoji-input="{buttonLabel:'Insert Emoji',wysiwyg:true}"></textarea>
  

如果您希望可编辑字段在键入时转换:( 等文本,则需要对该jquery插件进行分叉并稍微修改以解析更改时的输入文本以及在初始化。 (比如,几行代码)