2013-03-11 40 views
5

我爲redactor(一個wysiwyg編輯器)編寫了一個指令。它在一些黑客行爲後有效,但我想找出正確的方法。我面臨的主要挑戰是ng模型和redactor jquery插件之間的雙向綁定。我從wysiwyg編輯器聽取鍵盤和命令事件並更新模型。我還從外部編輯器編輯器中觀察模型更改,以便相應地更新編輯器編輯器。棘手的部分是:如何忽略反應器編輯器施加的ng模型更改(從綁定的前半部分開始)?Angular Directive - 如何設置與ng-model的雙向綁定

在下面的代碼,它會記住最後的值的主編編輯更新模型,而忽略模式的變革,如果模型的新值等於到最後一個值。我真的不確定這是否是實現這一目標的正確方法。在我看來,這是與角的雙向約束力,必須有一個方式的共同問題。謝謝!

<textarea ui-redactor='{minHeight: 500}' ng-model='content'></textarea> 

directive.coffee(抱歉的CoffeeScript)

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

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

    updateModel = -> 
     ngModel.$setViewValue updatedVal = elm.val() 
     scope.$apply() 

    options = 
     execCommandCallback: updateModel 
     keydownCallback: updateModel 
     keyupCallback: updateModel 

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

    angular.extend options, optionsInAttr 

    setTimeout -> 
     redactor = elm.redactor options 

    #watch external model change 
    scope.$watch attrs.ngModel, (newVal) -> 
     if redactor? and updatedVal isnt newVal 
     redactor.setCode(ngModel.$viewValue or '') 
     updatedVal = newVal 
+3

代替$腕錶(),你嘗試過實施ngModel。$渲染()?看來$ render()只會在Angular內部改變模型的時候被調用。在[fiddle](http://jsfiddle.net/mrajcok/SKgVS/)中,僅當我點擊鏈接(它以編程方式更改模型)時,纔會調用$ render()。 (因爲我沒有編碼許可證,所以我無法測試這個。) – 2013-03-11 17:24:53

+0

Mark,這對我很有用。非常感謝你! – KailuoWang 2013-03-11 18:10:43

+0

太棒了,很高興它的工作,並感謝讓我們知道。 – 2013-03-11 18:30:37

回答

0

馬克Rajcok給出瞭解決方案(謝謝!)的技巧是使用ngModel。$渲染(),而不是看$() 。

使用

ngModel.$render = -> 
    redactor?.setCode(ngModel.$viewValue or '') 

,而不是

scope.$watch attrs.ngModel, (newVal) -> 
    if redactor? and updatedVal isnt newVal 
    redactor.setCode(ngModel.$viewValue or '') 
    updatedVal = newVal 
+0

NG-模式?有什麼想法爲什麼? – 2013-05-03 08:18:32