触发 ng-model.$formatters 以编程方式运行 [英] Trigger ng-model.$formatters to run programmatically

查看:19
本文介绍了触发 ng-model.$formatters 以编程方式运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like a custom control that uses ngModel.$formatters to be able to format data as soon as a server dependency loads in. In my case, it needs to load a lookup table to go from one kind of id to another. $modelValue stores one thing $viewValue displays another. Pretty straight-forward stuff.

诀窍是,如果我的查找表未加载,则无法将格式设置为 $viewValue.

The trick is that if my lookup table isn't loaded, I can't do the formatting into a $viewValue.

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

Once my data loads, I need to do the following:

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

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

$render() doesn't work, this just moves the value from $viewValue into the UI control. $rollbackViewValue() looks promising, but that's only in an unstable version (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.
});

推荐答案

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

Looking at the code for ngModelController, it appears that what you stumbled upon (setting $modelValue to anything other than the current actual model value) is the accepted way to do this. As you say, the value you set is not used: it just triggers the update. Check its current value first to make sure it actually changes (or use a very unlikely value).

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

这是一个相关问题.

此外,还有一个主动拉取请求,看起来像一个官方"的方式即将推出.

Also, there is an active pull request that looks like an "official" way of doing this is forthcoming.

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

The reason it works is that ngModelController sets up a $watch that runs every digest cycle that compares $modelValue to the value that ng-model is bound to. If they don't match, it triggers the $formatters pipeline.

这篇关于触发 ng-model.$formatters 以编程方式运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆