TinyMCE <textarea>与AngularJS双向绑定

J86*_*J86 2 binding tinymce angularjs

是否可以将双向绑定<textarea></textarea>应用于已将TinyMCE应用于Rich Text Formatting的情况.

我无法上班!我可以让TinyMCE加载我的模型的内容,但是当我更新TinyMCE中的文本时,我的模型不会自动更新!

有办法吗?任何帮助将不胜感激.

谢谢.

jvd*_*ten 5

您可以通过创建自己的指令来完成此操作.

你需要做的是让你的指令在TinyMCE编辑器中的某些内容发生变化时同步你的模型.我没有使用TinyMCE,但是Wysihtml5.我想你可以重新制作这个以使用TinyMCE代替.

angular.module('directives').directive('wysihtml5', ['$timeout',
function ($timeout) {
    return {
        restrict: 'E',
        require: 'ngModel',
        template: "<textarea></textarea>", // A template you create as a HTML file (use templateURL) or something else...
        link: function ($scope, $element, attrs, ngModel) {

            // Find the textarea defined in your Template
            var textarea = $element.find("textarea");

            // When your model changes from the outside, use ngModel.$render to update the value in the textarea
            ngModel.$render = function () {
                textarea.val(ngModel.$viewValue);
            };

            // Create the editor itself, use TinyMCE in your case
            var editor = new wysihtml5.Editor(textarea[0],
                {
                    stylesheets: ["/style.css"],
                    parserRules: wysihtml5ParserRules,
                    toolbar: true,
                    autoLink: true,
                    useLineBreaks: false,
                });

            // Ensure editor is rendered before binding to the change event
            $timeout(function () {

                // On every change in the editor, get the value from the editor (textarea in case of Wysihtml5)
                // and set your model
                editor.on('change', function () {
                    var newValue = textarea.val();

                    if (!$scope.$$phase) {
                        $scope.$apply(function () {
                            ngModel.$setViewValue(newValue);
                        });
                    }
                });

            }, 500);
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的html页面中使用这个指令,如下所示:

<wysihtml5 ng-model="model.text" />
Run Code Online (Sandbox Code Playgroud)

如果您需要有关创建自己的指令的更多信息,请参阅以下链接:http://docs.angularjs.org/guide/directive