绑定bidirectionaly两个输入在AngularJs一个转换器 [英] Bind bidirectionaly two inputs for a converter in AngularJs

查看:135
本文介绍了绑定bidirectionaly两个输入在AngularJs一个转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我新的角度,我想(用于训练目的)写一个转换器。

我试图做的是像谷歌搜索页面结果转换器:的 https://www.google.com/search?q=1km+to+meter

基本上,它是捆绑在一起并做改变的东西转换两个输入。当您更新仪表输入它更新公里输入,相反也适用。

现在,我使用的过滤器进行转换(因为我觉得这份工作的那种凉)。你可以在这里找到一个活生生的例子: http://jsfiddle.net/FMXhJ/1/

正如你所看到计公里的伟大工程,但我不看我怎么可以做相反的方向。因此,它似乎也不会是解决这一问题的解决方案。

我想你的帮助,知道什么是做到这一点的最佳解决方案。

一些 $观看为输入控制器是一个很好的路要走?

解决方案

您可以只使用两种型号,并更新对方的 ngChange 事件:

http://jsfiddle.net/FMXhJ/2/

或者你可以使用观察家的确是:

http://jsfiddle.net/FMXhJ/3/

现在你最好通过具有通用的转换方法及型动物的单位作为一个阵列结构的数据 {名称:'公里',比'0.001'} 这样一个值转换到另一个就是有关合适的比率相乘。

I'm new to Angular and I'm trying (for training purposes) to write a converter.

What I'm trying to do is like the converter on Google search page result: https://www.google.com/search?q=1km+to+meter

Basically, it's two inputs bound together and doing conversion stuff on change. When you update the meter input it updates the kilometer input and the opposite also works.

For now, I've used a filter to do the conversion (because I find it kind of cool for the job). You can find a live example here: http://jsfiddle.net/FMXhJ/1/

As you can see meter to kilometer works great, but I don't see how could I do the opposite way. So it seems like it won't be the solution to tackle the issue.

I wanted your help to know what is the best solution to do it.

Some $watch on a controller for both input is a good way to go?

解决方案

You could just use two models and update each other on the ngChange event:

http://jsfiddle.net/FMXhJ/2/

Or you can use watchers indeed:

http://jsfiddle.net/FMXhJ/3/

Now you'd better structure your data by having a generic convert method and an array of differents units being {name: 'km', ratio: '0.001'}so converting a value to another is just about multiplying by the proper ratio.

这篇关于绑定bidirectionaly两个输入在AngularJs一个转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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