2013-11-15 31 views
2

是否有可能將雙向綁定應用於已將TinyMCE應用於Rich Text Formatting的<textarea></textarea>TinyMCE <textarea>與AngularJS綁定的兩種方式

我不能讓它工作!我可以讓TinyMCE加載我的模型的內容,但是當我更新TinyMCE中的文本時,我的模型不會自動更新!

有沒有辦法?任何幫助將不勝感激。

謝謝。

回答

5

你可以通過創建你自己的指令來做到這一點。

您需要做的是在TinyMCE編輯器中的某些內容發生更改時讓您的指令同步您的模型。我沒有使用TinyMCE,但Wysihtml5。我認爲你可以改造這個來代替使用TinyMCE。

angular.module('directives').directive('wysihtml5', ['$timeout', 
function ($timeout) { 
    return { 
     restrict: 'E', 
     require: 'ngModel', 
     template: "<textarea></textarea>", // A template you create as a HTML file (use templateURL) or something else... 
     link: function ($scope, $element, attrs, ngModel) { 

      // Find the textarea defined in your Template 
      var textarea = $element.find("textarea"); 

      // When your model changes from the outside, use ngModel.$render to update the value in the textarea 
      ngModel.$render = function() { 
       textarea.val(ngModel.$viewValue); 
      }; 

      // Create the editor itself, use TinyMCE in your case 
      var editor = new wysihtml5.Editor(textarea[0], 
       { 
        stylesheets: ["/style.css"], 
        parserRules: wysihtml5ParserRules, 
        toolbar: true, 
        autoLink: true, 
        useLineBreaks: false, 
       }); 

      // Ensure editor is rendered before binding to the change event 
      $timeout(function() { 

       // On every change in the editor, get the value from the editor (textarea in case of Wysihtml5) 
       // and set your model 
       editor.on('change', function() { 
        var newValue = textarea.val(); 

        if (!$scope.$$phase) { 
         $scope.$apply(function() { 
          ngModel.$setViewValue(newValue); 
         }); 
        } 
       }); 

      }, 500); 
     } 
    }; 
}]); 

然後你可以使用該指令在HTML頁面中是這樣的:

<wysihtml5 ng-model="model.text" /> 

這裏有一個鏈接,如果你需要創建自己的指令的詳細信息:http://docs.angularjs.org/guide/directive

0

也比較渲染功能從上面的指令到這個渲染函數from angular-ui-tinymce(https://github.com/angular-ui/ui-tinymce

ngModel.$render = function() { 
    if (!tinyInstance) { 
    tinyInstance = tinymce.get(attrs.id); 
    } 
    if (tinyInstance) { 
    tinyInstance.setContent(ngModel.$viewValue || ''); 
    } 

Plnkr:http://plnkr.co/edit/04AFkp?p=preview

但是,根據加載DOM的時機,您可能需要在指令上向上設置優先級。 :-)

0

這是我的解決方案使用自定義角度指令。 你需要使用jQuery與angularJS,TinyMCE 4和他們的jQuery插件。

myApp.directive('tinymce', function() { 
    return { 
     restrict: 'C', 
     require: 'ngModel', 
     link: function(scope, element, attrs, modelCtrl) { 
     element.tinymce({ 
      setup: function (e) { 
       e.on("change", function() { 
        modelCtrl.$setViewValue(element.val()); 
        scope.$apply(); 
       } 
      } 
     }); 
     } 
    } 
} 

然後在你的HTML:

<textarea class="tinymce" ng-model="data"></textarea> 

就是這樣,有樂趣。