33

我想将 CKEditor 文本绑定到ng-model文本。我的观点:

    <form name="postForm" method="POST" ng-submit="submit()" csrf-tokenized class="form-horizontal">
  

    <fieldset>
    <legend>Post to: </legend>
    <div class="control-group">
      <label class="control-label">Text input</label>
      <div class="controls">
        <div class="textarea-wrapper">
          <textarea id="ck_editor" name="text" ng-model="text" class="fullwidth"></textarea>
        </div>
        <p class="help-block">Supporting help text</p>
      </div>
    </div>

    <div class="form-actions">
      <button type="submit" class="btn btn-primary">Post</button>
      <button class="btn">Cancel</button>
      <button class="btn" onclick="alert(ckglobal.getDate())">Cancel123</button>
    </div>
  </fieldset>
</form>

控制器

      function PostFormCtrl($scope, $element, $attrs, $transclude, $http, $rootScope) {
      $scope.form = $element.find("form");
      $scope.text = "";
    
      $scope.submit = function() {
          $http.post($scope.url, $scope.form.toJSON()).
          success(function(data, status, headers, config) {
                  $rootScope.$broadcast("newpost");
                  $scope.form[0].reset();
              });
      };
    
      $scope.alert1 = function(msg) {
          var sval = $element.find("ckglobal");
          //$('.jquery_ckeditor').ckeditor(ckeditor);                                                                                                                      
          alert(sval);
      };
    }
    PostFormCtrl.$inject = ["$scope", "$element", "$attrs", "$transclude", "$http", "$rootScope"];

我想在$scope.text表单提交时设置 CKEditor 值。

4

7 回答 7

76

CKEditor 在输入时不会更新 textarea,所以你需要注意它。

这是一个使 ng-model 绑定与 CK 一起工作的指令:

angular.module('ck', []).directive('ckEditor', function() {
  return {
    require: '?ngModel',
    link: function(scope, elm, attr, ngModel) {
      var ck = CKEDITOR.replace(elm[0]);

      if (!ngModel) return;

      ck.on('pasteState', function() {
        scope.$apply(function() {
          ngModel.$setViewValue(ck.getData());
        });
      });

      ngModel.$render = function(value) {
        ck.setData(ngModel.$viewValue);
      };
    }
  };
});

在 html 中,只需使用:

<textarea ck-editor ng-model="value"></textarea>

前面的代码将在每次更改时更新 ng-model。

如果您只想在保存时更新绑定,请覆盖“保存”插件,除了触发“保存”事件之外什么都不做。

// modified ckeditor/plugins/save/plugin.js
CKEDITOR.plugins.registered['save'] = {
  init: function(editor) {
    var command = editor.addCommand('save', {
      modes: {wysiwyg: 1, source: 1},
      readOnly: 1,
      exec: function(editor) {
        editor.fire('save');
      }
    });

    editor.ui.addButton('Save', {
      label : editor.lang.save,
      command : 'save'
    });
  }
};

然后,在指令中使用这个事件:

angular.module('ck', []).directive('ckEditor', function() {
  return {
    require: '?ngModel',
    link: function(scope, elm, attr, ngModel) {
      var ck = CKEDITOR.replace(elm[0]);

      if (!ngModel) return;

      ck.on('save', function() {
        scope.$apply(function() {
          ngModel.$setViewValue(ck.getData());
        });
      });
    }
  };
});
于 2012-08-18T19:29:19.793 回答
7

如果您只是想以角度检索编辑器文本区域中的文本,请调用CKEDITOR.instances.editor1.getData();以直​​接在 angularjs 函数中获取值。见下文。

在你的 html

在 test.controller.js

(function () {
    'use strict';

    angular
        .module('app')
            .controller('test', test);

    test.$inject = []; 

    function test() {

        //this is to replace $scope
        var vm = this;

        //function definition
        function postJob()
        {          
            vm.Description = CKEDITOR.instances.editor1.getData();
            alert(vm.Description);
        }
    } 
})();
于 2015-01-09T00:54:33.623 回答
6

Vojta回答部分工作

在这篇文章中,我找到了解决方案

https://stackoverflow.com/a/18236359/1058096

最终代码:

.directive('ckEditor', function() {
                return {
                    require : '?ngModel',
                    link : function($scope, elm, attr, ngModel) {

                        var ck = CKEDITOR.replace(elm[0]);

                        ck.on('instanceReady', function() {
                            ck.setData(ngModel.$viewValue);
                        });

                        ck.on('pasteState', function() {
                            $scope.$apply(function() {
                                ngModel.$setViewValue(ck.getData());
                            });
                        });

                        ngModel.$render = function(value) {
                            ck.setData(ngModel.$modelValue);
                        };
                    }
                };
            })

编辑:删除未使用的括号

于 2013-09-01T02:47:53.250 回答
1

感谢 Vojta 的出色指导。有时它不加载。这是修复该问题的修改版本。

angular.module('ck', []).directive('ckEditor', function() {
  var calledEarly, loaded;
  loaded = false;
  calledEarly = false;

  return {
    require: '?ngModel',
    compile: function(element, attributes, transclude) {
      var loadIt, local;

      local = this;
      loadIt = function() {
        return calledEarly = true;
      };

      element.ready(function() {
        return loadIt();
      });

      return {
        post: function($scope, element, attributes, controller) {
          if (calledEarly) {
            return local.link($scope, element, attributes, controller);
          }
          loadIt = (function($scope, element, attributes, controller) {
            return function() {
              local.link($scope, element, attributes, controller);
            };
          })($scope, element, attributes, controller);
        }
      };
    },

    link: function($scope, elm, attr, ngModel) {
      var ck;
      if (!ngModel) {
        return;
      }

      if (calledEarly && !loaded) {
        return loaded = true;
      }
      loaded = false;

      ck = CKEDITOR.replace(elm[0]);
      ck.on('pasteState', function() {
        $scope.$apply(function() {
          ngModel.$setViewValue(ck.getData());
        });
      });

      ngModel.$render = function(value) {
        ck.setData(ngModel.$viewValue);
      };
    }
  };
});

或者如果你在咖啡脚本中需要它

angular.module('ck', []).directive('ckEditor', ->
  loaded = false
  calledEarly = false
  {
    require: '?ngModel',
    compile: (element, attributes, transclude) ->
      local = @
      loadIt = ->
        calledEarly = true

      element.ready ->
        loadIt()
      post: ($scope, element, attributes, controller) ->
        return local.link $scope, element, attributes, controller if calledEarly

        loadIt = (($scope, element, attributes, controller) ->
          return ->
            local.link $scope, element, attributes, controller
        )($scope, element, attributes, controller)
    link: ($scope, elm, attr, ngModel) ->
      return unless ngModel

      if (calledEarly and not loaded)
        return loaded = true
      loaded = false

      ck = CKEDITOR.replace(elm[0])

      ck.on('pasteState', ->
        $scope.$apply( ->
          ngModel.$setViewValue(ck.getData())
        )
      )

      ngModel.$render = (value) ->
        ck.setData(ngModel.$viewValue)
  }
)
于 2013-04-28T06:27:49.713 回答
1

如果您想在一个页面中使用多个编辑器,这只是为了记录,这可以派上用场:

mainApp.directive('ckEditor', function() {
    return {
        restrict: 'A', // only activate on element attribute
        scope: false,
        require: 'ngModel',
        controller: function($scope, $element, $attrs) {}, //open for now
        link: function($scope, element, attr, ngModel, ngModelCtrl) {
            if(!ngModel) return; // do nothing if no ng-model you might want to remove this
            element.bind('click', function(){
                for(var name in CKEDITOR.instances)
                    CKEDITOR.instances[name].destroy();
                var ck = CKEDITOR.replace(element[0]);
                ck.on('instanceReady', function() {
                    ck.setData(ngModel.$viewValue);
                });
                ck.on('pasteState', function() {
                    $scope.$apply(function() {
                        ngModel.$setViewValue(ck.getData());
                    });
                });
                ngModel.$render = function(value) {
                    ck.setData(ngModel.$viewValue);
                };
            });
        }
    }
});

这将销毁所有以前的 ckeditor 实例并创建一个新实例。

于 2013-09-05T22:45:46.670 回答
0

带有 CKEditor v5 的 ES6 示例。

注册指令使用:

   angular.module('ckeditor', []).directive('ckEditor', CkEditorDirective.create)

指示:

import CkEditor from "@ckeditor/ckeditor5-build-classic";
export default class CkEditorDirective {

   constructor() {
     this.restrict = 'A';
     this.require = 'ngModel';
   }

  static create() {
    return new CkEditorDirective();
  }

  link(scope, elem, attr, ngModel) {
    CkEditor.create(elem[0]).then((editor) => {
      editor.document.on('changesDone', () => {
        scope.$apply(() => {
          ngModel.$setViewValue(editor.getData());
        });
      });

      ngModel.$render = () => {
        editor.setData(ngModel.$modelValue);
      };

      scope.$on('$destroy', () => {
        editor.destroy();
      });
    })
  }
}
于 2017-10-17T08:47:16.447 回答
0

现在有一个“更改”事件可以用于此。

这是我刚刚创建的一个指令,它有几个不同的工具栏配置选项,我正在使用 jQuery 适配器来初始化 ckeditor。有关更多信息,请查看此博客文章

(function () {
    'use strict';

    angular
        .module('app')
        .directive('wysiwyg', Directive);

    function Directive($rootScope) {
        return {
            require: 'ngModel',
            link: function (scope, element, attr, ngModel) {
                var editorOptions;
                if (attr.wysiwyg === 'minimal') {
                    // minimal editor
                    editorOptions = {
                        height: 100,
                        toolbar: [
                            { name: 'basic', items: ['Bold', 'Italic', 'Underline'] },
                            { name: 'links', items: ['Link', 'Unlink'] },
                            { name: 'tools', items: ['Maximize'] },
                            { name: 'document', items: ['Source'] },
                        ],
                        removePlugins: 'elementspath',
                        resize_enabled: false
                    };
                } else {
                    // regular editor
                    editorOptions = {
                        filebrowserImageUploadUrl: $rootScope.globals.apiUrl + '/files/uploadCk',
                        removeButtons: 'About,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Save,CreateDiv,Language,BidiLtr,BidiRtl,Flash,Iframe,addFile,Styles',
                        extraPlugins: 'simpleuploads,imagesfromword'
                    };
                }

                // enable ckeditor
                var ckeditor = element.ckeditor(editorOptions);

                // update ngModel on change
                ckeditor.editor.on('change', function () {
                    ngModel.$setViewValue(this.getData());
                });
            }
        };
    }
})();

这是几个如何在 HTML 中使用指令的示例

<textarea ng-model="vm.article.Body" wysiwyg></textarea>
<textarea ng-model="vm.article.Body" wysiwyg="minimal"></textarea>

这是我从 CDN 中包含的 CKEditor 脚本,以及我下载的几个额外插件,以启用从 word 中粘贴图像。

<script src="//cdn.ckeditor.com/4.5.7/full/ckeditor.js"></script>
<script src="//cdn.ckeditor.com/4.5.7/full/adapters/jquery.js"></script>
<script type="text/javascript">
    // load extra ckeditor plugins
    CKEDITOR.plugins.addExternal('simpleuploads', '/js/ckeditor/plugins/simpleuploads/plugin.js');
    CKEDITOR.plugins.addExternal('imagesfromword', '/js/ckeditor/plugins/imagesfromword/plugin.js');
</script>
于 2016-04-28T03:05:38.150 回答