10

我尝试将 Beautifull WYSIWYG Redactor ( http://imperavi.com/redactor/ ) 集成到自定义 AngularJS 指令中。

Visualy 它可以工作,但我的自定义指令与 ng-model 不兼容(我不明白为什么)

这就是你可以使用我的指令的方式:

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

这是指令代码:

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

最后这是小提琴-> http://fiddle.jshell.net/MyBoon ​​/STLW5/

4

5 回答 5

4

我根据 Angular-UI 的 TinyMCE 指令制作了一个。这一个也听格式按钮的点击。它还处理模型在指令之外更改的情况。

Directive.coffee(对不起咖啡脚本)

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>
于 2013-03-09T03:55:38.897 回答
4

更新 --- Rails 4.2 --- Angular-Rails 1.3.14

好吧,伙计们,经过大量研究和其他成员对堆栈溢出的帮助,这里有一个解决方案,它直接输入控制器 $scope 和应用到 textarea 的 ng-model:

** 渲染原始 HTML **

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

过滤器的功劳

指示:

# 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

最后一行更新原因

在 HTML 视图中:

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

和控制器:

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

为了防止 TypeError 与 redactor 在调用操作之前将一个值填充到 textarea 中,这对我来说最适合保留格式:

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

如果您遇到 CSRF 错误,这将解决该问题:

# 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')

]

非常感谢:AngularJS 和 Redactor 插件

最后....

如果您使用 ng-repeat 创建这些编辑器文本区域并且无法访问范围,请查看以下答案:Accessing the model inside a ng-repeat

于 2013-05-07T21:32:05.577 回答
1

看看这个小提琴是不是你想要的。

ng-model 可以设置为内容:

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

在链接函数内部,el 已经设置为定义指令的元素,因此id不需要 an。el 已经是一个包装好的 jQuery 元素。

链接功能:

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()));
于 2013-01-20T00:40:23.930 回答
1

我的解决方案是

1) 克隆https://github.com/dybskiy/redactor-js.git 2) 包括 jquery、redactor.js、redactor.css 3) 添加标签:<textarea wysiwyg ng-model="post.content" cols="18" required></textarea>到您的 html 正文 4) 添加指令:

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

最好的问候, Jeliuc Alexandr

于 2013-04-27T16:26:18.043 回答
1

上述解决方案不适用于所有情况,因此我使用它们创建了以下指令,使模型和编辑器保持同步。

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

});

只需将 redactor 模块添加为依赖项,并将以下内容添加到您的 html 中:

注意:升级到 9.1.1 版本后我必须更新代码

这是新版本:

    .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);
              };
          }
        };
      });
于 2013-08-19T06:09:00.770 回答