AngularJS & Redactor Plugin

僤鯓⒐⒋嵵緔 提交于 2019-11-30 07:43:47

I was looking for the same answer today and made a directive to solve it:

angular.module('Module', []).directive("redactor", function() {
  return {
    require: '?ngModel',
    link: function($scope, elem, attrs, controller) {   

      controller.$render = function() {

        elem.redactor({
          keyupCallback: function() {
            $scope.$apply(controller.$setViewValue(elem.getCode()));
          },
          execCommandCallback: function() {
            $scope.$apply(controller.$setViewValue(elem.getCode()));
          }
        });

        elem.setCode(controller.$viewValue);
      };
    }
  };
});

Then you can just use the following HTML:

<textarea ng-model="yourModel" redactor></textarea>

The model will be updated on each keyUp and whenever the user clicks on a button in the toolbar. The model will contain the HTML code.

I have just started out with AngularJS so please let me know if there are better ways to do this or if I broke some conventions I am still unaware of.

For those who find the accepted answer not working as I did. This is the working one (with Angular v1.1.5)

angular.module('Module', []).directive("redactor", function() {
        return {
            require: '?ngModel',
            link: function($scope, elem, attrs, controller) {
                controller.$render = function() {
                    elem = $(elem);
                    elem.val(controller.$viewValue);
                    elem.redactor({

                        changeCallback: function() {
                            $scope.$apply(controller.$setViewValue(elem.val()));
                        }

                    });

                };
            }
        };
    });

The changeCallback is way too much better than other callbacks combined and in my case, I have to cast the elem to a Jquery element. I also found that the setCode and getCode is not available at all. May be it is a different version.

Use this AngularJS module for "RedactorJS": https://github.com/TylerGarlick/angular-redactor

It worked fine for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!