Bind Ckeditor value to model text in angularjs and rails

I want to bind ckeditor text to ng-model text

My View

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

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

Thk's in advance

CKEditor does not update textarea while typing, so you need to take care of it.

Here's a directive that will make ng-model binding work with 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);
      };
    }
  };
});

In html, just use:

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

The previous code will update ng-model on every change.

If you only want to update binding on save, override "save" plugin, to not do anything but fire "save" event.

// 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'
    });
  }
};

And then, use this event inside the directive:

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

the Vojta answer work partly

in this post I found a solution

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

the final code:

.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);
                        };
                    }
                };
            })

edit: removed unused brackets

Thanks to Vojta for the excellent directive. Sometimes it doesn't load. Here is a modified version to fix that issue.

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

or if you need it in coffeescript

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

And just for the record if you want to use multiple editors in one page this can come in handy:

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

This will destroy all previous instances of ckeditor and create a new one.

If you simply want to retrieve text in the editor textarea in angular, call CKEDITOR.instances.editor1.getData(); to get the value directly in an angularjs function. See below.

In your html

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