我为 redactor(一个所见即所得的编辑器)写了一个指令。经过一些黑客攻击后它可以工作,但我想找出正确的方法。对我来说主要的挑战是 ng-model 和 redactor jquery 插件之间的双向绑定(bind)。我从所见即所得编辑器中收听 keyup 和命令事件并更新模型。我还从 redactor 编辑器外部观察模型更改,以便我可以相应地更新 redactor 编辑器。棘手的部分是:如何忽略 react 器编辑器强加的 ng-model 更改(从绑定(bind)的前半部分开始)?
在下面的代码中,它会记住编辑器编辑器更新到模型的最后一个值,如果模型的新值等于最后一个值,则忽略模型更改。我真的不确定这是否是实现此目标的正确方法。在我看来,这是 Angular 中双向绑定(bind)的常见问题,必须有一种正确的方式。谢谢!
<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
最佳答案
Mark Rajcok 给出了解决方案(谢谢!)诀窍是使用 ngModel.$render() 而不是 $watch()。
使用
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
关于javascript - Angular 指令 - 如何使用 ng-model 设置双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15342869/