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

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

问题描述

我想要一个使用 ngModel.$formatters 的自定义控件a>以便能够在服务器依赖项加载后立即格式化数据.就我而言,它需要加载查找表才能从一种ID转换为另一种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 -> $formatters -> $viewValue
  • 启动管道
  • ngModel.$formatters.push(myFormatter)
  • Tell ngModel to start the pipeline from $modelValue -> $formatters -> $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设置为当前实际模型值以外的任何值)是可以接受的方式去做这个.就像您说的那样,不会使用您设置的值:它只会触发更新.首先检查其当前值以确保其实际更改(或使用不太可能的值).

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,该$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天全站免登陆