10

I try to integrate The beautifull WYSIWYG Redactor (http://imperavi.com/redactor/) in an custom AngularJS directive.

Visualy it works, but my custom directive is not compatible with ng-model (and I don't understand why)

This is how you can use my directive :

<wysiwyg ng-model="edited.comment" id="contactEditCom" content="{{content}}" required></wysiwyg>

And this is the directive code :

var myApp = angular.module('myApp', []);
myApp.directive("wysiwyg", function(){

var linkFn = function(scope, el, attr, ngModel) {

    scope.redactor = null;

    scope.$watch('content', function(val) {
        if (val !== "")
        {
            scope.redactor = $("#" + attr.id).redactor({
                focus : false,
                callback: function(o) {
                    o.setCode(val);
                    $("#" + attr.id).keydown(function(){
                        scope.$apply(read);
                    });
                }
            });
        }
    });

    function read() {
        var content = scope.redactor.getCode();
        console.log(content);
        if (ngModel.viewValue != content)
        {
            ngModel.$setViewValue(content);
            console.log(ngModel);
        }
    }

};

 return {
     require: 'ngModel',
     link: linkFn,
     restrict: 'E',
     scope: {
         content: '@'
     },
     transclude: true
 };
});

And finally this is the fiddle -> http://fiddle.jshell.net/MyBoon/STLW5/

MyBoon
  • 1,290
  • 1
  • 10
  • 18
  • In read(), ngModel.viewValue should be ngModel.$viewValue. What do you mean by "my custom directive is not compatible with ng-model"? – Mark Rajcok Jan 12 '13 at 17:04
  • All I want is that my custom directive works like other inputs. For example when you write this : the scope variable 'edited.input' will be fill in if a the text is typed. I try to have the same behavior with my directive. – MyBoon Jan 17 '13 at 09:17

5 Answers5

4

I made one based on Angular-UI's TinyMCE directive. This one also listen to format button clicks. It also handles the case when the model is changed outside the directive.

directive.coffee (sorry for the coffeescript)

angular.module("ui.directives").directive "uiRedactor", ["ui.config", (uiConfig) ->

  require: "ngModel"
  link: (scope, elm, attrs, ngModelCtrl) ->
    redactor = null

    getVal = -> redactor?.getCode()

    apply = ->
      ngModelCtrl.$pristine = false
      scope.$apply()

    options =
      execCommandCallback: apply
      keydownCallback: apply
      keyupCallback: apply

    scope.$watch getVal, (newVal) ->
      ngModelCtrl.$setViewValue newVal unless ngModelCtrl.$pristine


    #watch external model change
    ngModelCtrl.$render = ->
      redactor?.setCode(ngModelCtrl.$viewValue or '')

    expression = if attrs.uiRedactor then scope.$eval(attrs.uiRedactor) else {}

    angular.extend options, expression

    setTimeout ->
      redactor = elm.redactor options
]  

html

<textarea ui-redactor='{minHeight: 500}' ng-model='content'></textarea>
KailuoWang
  • 1,304
  • 1
  • 12
  • 24
4

UPDATED --- Rails 4.2 --- Angular-Rails 1.3.14

Alright guys, after lots of research and some help from other members on stack overflow here is a solution that feeds straight into the controller $scope and into the ng-model you apply to the textarea:

** Render Raw HTML**

# Filter for raw HTML
app.filter "unsafe", ['$sce', ($sce) ->
    (htmlCode) ->
        $sce.trustAsHtml htmlCode
]

Credit for Filter

Directive:

# For Redactor WYSIWYG
app.directive "redactor", ->
require: "?ngModel"
link: ($scope, elem, attrs, controller) ->
    controller.$render = ->
        elem.redactor
            changeCallback: (value) ->
                $scope.$apply controller.$setViewValue value
            buttons: ['html', '|', 'formatting', '|',
                'fontcolor', 'backcolor', '|', 'image', 'video', '|',
                'alignleft', 'aligncenter', 'alignright', 'justify', '|',
                'bold', 'italic', 'deleted', 'underline', '|',
                'unorderedlist', 'orderedlist', 'outdent', 'indent', '|',
                'table', 'link', 'horizontalrule', '|']
            imageUpload: '/modules/imageUpload'
        elem.redactor 'insert.set', controller.$viewValue

Last line update reason

in the HTML View:

<div ng-controller="PostCtrl">  
    <form ng-submit="addPost()">
        <textarea ng-model="newPost.content" redactor required></textarea>
        <br />
        <input type="submit" value="add post">
    </form>

    {{newPost.content}} <!-- This outputs the raw html with tags -->
    <br />
    <div ng-bind-html="newPost.content | unsafe"></div> <!-- This outputs the html -->
</div>

And the Controller:

$scope.addPost = ->     
    post = Post.save($scope.newPost)
    console.log post
    $scope.posts.unshift post
    $scope.newPost.content = "<p>Add a new post...</p>"

To PREVENT a TypeError with redactor populate a value into the textarea before the action is called, this worked best for me to preserve formatting:

# Set the values of Reactor to prevent error
    $scope.newPost = {content: '<p>Add a new post...</p>'}

If you are on running into CSRF errors this will solve that problem:

# Fixes CSRF Error OR: https://github.com/xrd/ng-rails-csrf
app.config ["$httpProvider", (provider) ->
    provider.defaults.headers.common['X-CSRF-Token'] = angular.element('meta[name=csrf-token]').attr('content')

]

Much Thanks to: AngularJS & Redactor Plugin

Lastly....

If you are using an ng-repeat to create these redactor text areas and are having trouble accessing the scope, check out this answer: Accessing the model inside a ng-repeat

Community
  • 1
  • 1
blnc
  • 4,384
  • 1
  • 28
  • 42
  • 1
    Now you can use the new "changeCallback". "execCommandCallback" is not used anymore. See: changeCallback: function(html) {} – benske Sep 19 '13 at 06:49
1

See if this fiddle is what you want.

ng-model can be set to content:

<wysiwyg ng-model="content" required></wysiwyg>

Inside the linking function, el is already set to the element where the directive is defined, so an id is not needed. And el is already a wrapped jQuery element.

Link function:

var linkFn = function (scope, el, attr, ngModel) {
    scope.redactor = el.redactor({
        focus: false,
        callback: function (o) {
            o.setCode(scope.content);
            el.keydown(function () {
                console.log(o.getCode());
                scope.$apply(ngModel.$setViewValue(o.getCode()));
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
1

My solution is

1) clone https://github.com/dybskiy/redactor-js.git 2) include jquery, redactor.js, redactor.css 3) add tag: <textarea wysiwyg ng-model="post.content" cols="18" required></textarea> to your html body 4) add directive:

yourapp.directive('wysiwyg', function () {
  return {
    require: 'ngModel',
    link: function (scope, el, attrs, ngModel) {
      el.redactor({
        keyupCallback: function(obj, e) {
            scope.$apply(ngModel.$setViewValue(obj.getCode()));
        }
      });
      el.setCode(scope.content);
    }
  };
});

Best regards, Jeliuc Alexandr

1

The above solutions didn't work for me for all situations so I used them to create the following directive that does keep model and redactor in sync.

angular.module('redactor', [])

.directive('redactor', function () { return { require: '?ngModel', link: function (scope, el, attrs, ngModel) {

  // Function to update model
  var updateModel = function() {
        scope.$apply(ngModel.$setViewValue(el.getCode()));
    };

  // Get the redactor element and call update model
  el.redactor({
    keyupCallback: updateModel,
    keydownCallback: updateModel,
    execCommandCallback: updateModel,
    autosaveCallback: updateModel
  });

  // Call to sync the redactor content
          ngModel.$render = function(value) {
        el.setCode(ngModel.$viewValue);
    };
  }
};

});

Just add the redactor module as a dependency and the following to your html:

Note: I had to update the code after upgrading to version 9.1.1

Here is the new version:

    .directive('redactor', function () {
        return {
          require: '?ngModel',
          link: function (scope, el, attrs, ngModel) {

            var updateModel, errorHandling;
            // Function to update model
            updateModel = function() {
              if(!scope.$$phase) {
                  scope.$apply(ngModel.$setViewValue(el.redactor('get')));
                }
              };

            uploadErrorHandling = function(response)
              {
                console.log(response.error);
                alert("Error: "+ response.error);
              }; 

            // Get the redactor element and call update model
            el.redactor({
              minHeight: 100,
              buttons: ['formatting', '|', 'bold', 'italic', 'deleted', '|',
              'unorderedlist', 'orderedlist', 'outdent', 'indent', '|',
              'image', 'video', 'file', 'table', 'link', '|', 'alignment', '|', 'horizontalrule'],
              keyupCallback: updateModel,
              keydownCallback: updateModel,
              changeCallback: updateModel,
              execCommandCallback: updateModel,
              autosaveCallback: updateModel,
              imageUpload: '/file/upload/image',
              imageUploadErrorCallback: uploadErrorHandling,
              imageGetJson: '/api/v1/gallery'
              });

            // Call to sync the redactor content
              ngModel.$render = function(value) {
                  el.redactor('set', ngModel.$viewValue);
              };
          }
        };
      });
Dan G
  • 11
  • 2