Work with elm and select

后端 未结 5 1017
既然无缘
既然无缘 2021-02-07 04:41

I try to understand how elm works with a custom example.

durationOption duration =
  option [value (toString duration) ] [ text (toString duration)]

view : Mode         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 05:09

    An example with onInput handler (you can also check the Ellie):

    module Main exposing (main)
    
    import Browser import Html exposing (Html, button, div, text, select, option) import Html.Attributes exposing (value, selected) import Html.Events exposing (onInput) import Dict exposing (Dict)
    
    type alias Model =
        { options : Dict Int (String, Bool)
        }
    
    
    initialModel : Model initialModel =
        { options = Dict.fromList [(0, ("All time", False)), (1, ("One week", True)), (2, ("24h", False))] 
        }
    
    
    type Msg
        = Select String
    
    
    update : Msg -> Model -> Model update msg model =
        case msg of
            Select value ->
                case String.toInt value of
                    Just selectedID ->
                        let
                            changeSelection id (label, _) =
                                if id == selectedID then
                                    (label, True)
                                else
                                    (label, False)
                        in
                        {model | options = Dict.map changeSelection model.options}
    
                    Nothing ->
                        model
    
    
    
    view : Model -> Html Msg view model =
        let
            toOption (id, (label, isSelected)) =
                option [value (String.fromInt id), selected isSelected] [text label]
        in
        div []
            [ select [onInput Select] (List.map toOption <| Dict.toList model.options)
            , div [] [text "DEBUG"]
            , div [] [text <| Debug.toString model.options]
            ]
    
    
    main : Program () Model Msg main =
        Browser.sandbox
            { init = initialModel
            , view = view
            , update = update
            }
    

提交回复
热议问题