javascript - Angular 指令 - 如何使用 ng-model 设置双向绑定(bind)

标签 javascript angularjs angularjs-directive

我为 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/

相关文章:

javascript - 如何锁定任何浏览器的屏幕宽度?

java - 如何使用 Spring Security 和 AngularJS 应用程序构建中央标志架构

javascript - View 不更新为范围值更新

AngularJS ng-if 在 $compile 后不删除元素

angularjs - 在 openlayer Angular 指令缩放按钮不显示

javascript - Mongoose:如何在变量给定的索引处更新数组中的值?

php - JavaScript 和 PHP 之间的通信

php - 在 php、ajax 或 javascript 中加载进度?

javascript - 使用 angular-chart.js 在条形图中手动设置 y 轴刻度

html - 使用 AngularJS、ui.Router 和 yeoman Livereload Html5 Pushstate