Bind Ckeditor value to model text in AngularJS and Rails

Viewed 31615

I want to bind CKEditor text to ng-model text. My View:

    <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>

controller

      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"];

I want to set CKEditor value in $scope.text at the time of form submit.

7 Answers

ES6 example with CKEditor v5.

Register directive using:

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

Directive:

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();
      });
    })
  }
}
Related