Angular JS - 在文本区域中显示和编辑模型并在模型更改时更新

Angular JS - display and edit model in textarea AND update when model changes

我刚从这里过来post:

Angular JS display and edit model in textarea

这对我想要实现的目标非常有帮助,但我需要更进一步,并在模型值更改时更新文本区域。我正在与来自上面 post 的 @JustMaier 的最后一个 example 合作。我想我需要添加一个 $watch 但不确定 how/where 是否准确。感谢您对此的帮助,谢谢!

是的,你是对的。它实际记录的 ngModel 不会观察深度变化,因此当模型发生深度变化时不会 zpdate 视图:

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

因此您需要将 ngModel 值添加到指令范围以便在其上使用 $watch:

scope:{'ngModel':'='}

然后将更新视图值的手表添加到指令 link 函数中:

scope.$watch ('ngModel', function (newval) { 
  ngModel.$viewValue = toJson(newval);
  ngModel.$render();
}, true);

查看演示: http://codepen.io/anon/pen/xbWamy

您可以 watch 您在 directive 中的 model 值并在更改时触发 formatters

scope.$watch(function() {
    return ngModel.$modelValue;
}, function(modelValue) {
    // trigger the formatters
    ngModel.$modelValue = '';
}, true);

DEMO