0

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

Google converter

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?

Cyril F
  • 1,842
  • 2
  • 19
  • 35
  • This awesome reality about finding the answer when you post the question just happened once again.. I think this is my answer: http://stackoverflow.com/a/17626761/1410020 – Cyril F Feb 22 '14 at 22:41

1 Answers1

4

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.

floribon
  • 19,175
  • 5
  • 54
  • 66