5

In AngularJS, ng-options lets one specify an array of any values, not just strings, while preserving types. For example, I might create an HTML select using ng-options over an array of integers. When an option is selected, the integer value is placed into the model—no string-to-int conversion necessary.

In Elm, an option's value attribute accepts only a string, and thus the select's onInput event sends back a string. Then I have to manually convert it to an int.

Does Elm have any equivalent to AngularJS's ng-options? Or any way to use a select with arbitrary, even non-scalar, values?

1
  • Well, I'm not sure you'd want to use it, but I did make exercise of this question in the form of a blog and a package.
    – toastal
    Jan 14, 2017 at 6:53

2 Answers 2

9

There isn't really a way to do this. You're going to have to parse from a string to your desired type and back. You could wrap a <select> with Prism-based API.

Give me a couple hours and I'll write a tiny library for that after work... :D

EDIT:

Package - http://package.elm-lang.org/packages/toastal/select-prism/latest

Blog Post - https://toast.al/posts/softwarecraft/2017-01-13_playing-with-prisms-for-the-not-so-isomorphic

2
  • This is very helpful. I'm new to Elm and hadn't encountered Prism yet, so I'm definitely going to study this more. Thanks for the blog post too! Jan 19, 2017 at 19:06
  • 1
    Take it with a grain of salt. Optics are not considered a best practice by some FP people--others love it. You could easily re-implement this library with an explicit get/set parameters rather than passing in a Prism, but where's the fun in learning something new in that??
    – toastal
    Jan 19, 2017 at 21:04
3

You might also be interested in my elm-select helper library. It doesn't do all that cool Prism / Lens stuff, but it might be simpler in some cases:

http://package.elm-lang.org/packages/lgastako/elm-select/1.0.0/Select

Full example code here:

https://github.com/lgastako/elm-select/blob/master/src/Main.elm

2
  • That's pretty good too. I'm livid that you thought Lenses and Prisms were "cool". :)
    – toastal
    Jan 14, 2017 at 18:04
  • This is great! I'm accepting @toastal's answer because of its depth, but honestly I'll probably end up using your library since it's so simple. Thanks! Jan 19, 2017 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.