【问题标题】:Trigger ng-model.$formatters to run programmatically触发 ng-model.$formatters 以编程方式运行
【发布时间】:2014-10-15 16:45:32
【问题描述】:

我想要一个使用 ngModel.$formatters 的自定义控件,以便能够在服务器依赖项加载后立即格式化数据。在我的情况下,它需要加载查找表以从一种 id 转到另一种. $modelValue 存储一件事 $viewValue 显示另一件事。非常直接的东西。

诀窍是,如果我的查找表没有加载,我无法将格式设置为 $viewValue。

加载数据后,我需要执行以下操作:

  • ngModel.$formatters.push(myFormatter)
  • 告诉 ngModel 从$modelValue -> $formatters -> $viewValue 开始管道

$render() 不起作用,这只是将值从$viewValue 移动到 UI 控件中。 $rollbackViewValue() 看起来很有希望,但这只是不稳定的版本 (1.3.0-beta.18)。

代码示例:

mappingTable.load().then(function(data){
  mappingData = data;
  ngModel.$formatters.push(myFormatter); // needs mappingData in order to function
  // TODO: Tell ngModel to run the existing $modelValue through $formatters to calculate a  new $viewValue and $render it
  //ngModel.$render() // doesn't work, only puts the $viewValue in the DOM element.
});

【问题讨论】:

  • 奇怪的是,我可以在数据加载后设置ngModel.$modelValue = 'foo'(字面意思是 foo)。这会导致管道运行,但与之前的模型值相反。最后,modelValue是我想要的,viewValue是我想要的解析后的版本,'foo'无处可寻。完美运行,但我不相信/不理解它。
  • 尝试调用$scope.$apply(),这将触发新的$digest循环,该循环应该使用更新的$formatters

标签: javascript angularjs angular-ngmodel


【解决方案1】:

查看 ngModelController 的代码,您发现(将 $modelValue 设置为当前实际模型值以外的任何值)似乎是公认的方法。正如您所说,您设置的值没有被使用:它只是触发更新。首先检查它的当前值以确保它确实发生了变化(或使用一个非常不可能的值)。

if (ngModel.$modelValue == 'bar')
    ngModel.$modelValue = 'foo';
else
    ngModel.$modelValue = 'bar';

这是related question

此外,还有一个 active pull request 看起来像是即将推出的“官方”方式。

它起作用的原因是 ngModelController 设置了一个 $watch,它运行每个摘要循环,将 $modelValue 与 ng-model 绑定的值进行比较。如果它们不匹配,则会触发$formatters 管道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多