Elm 自动完成用户输入

Elm Autocomplete On User Input

我是 Elm 的新手。我在网页上有一个输入字段。当用户在输入字段中输入时,我想查询一个单词列表(存储在 initialModel 中)并根据输入字段中输入的内容给出完成建议。我想我需要 Html.Events 按键,所以我已经导入了它。我知道我还需要一个更新函数,所以我包含了一个空函数。这是我到目前为止的代码。提前致谢。

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)

import StartApp.Simple as StartApp

-- MODEL

type alias Model =
  {
    words: List String
  }

initialModel : Model
initialModel =
  {
    words =
      [ "chair", "sofa", "table", "stove", "cabinet", "tv", "rug", "radio", "stereo" ]
  }


-- UPDATE
update =
  {

  }


-- VIEW

title : String -> Html
title message =
  message
    |> Html.text


pageHeader : Html
pageHeader =
  h1
    [  ]
    [ title "Hello" ]


pageFooter : Html
pageFooter =
  footer
    [  ]
    [ a [ href "#" ]
        [ text "Hello" ]
    ]

inputField : Html
inputField =
  input
    [ type' "text" ]
    [ ]


view : Html
view =
  div
    [ id "container" ]
    [ pageHeader
      , inputField
      , pageFooter
    ]

-- BRING MODEL, VIEW AND UPDATE TOGETHER

main =
  view
  -- StartApp.start
  --   {
  --     model = initialModel
  --     , view = view
  --     , update = update
  --   }

您的模型需要跟踪文本框的当前值。您可以先创建一个 SetValue 操作,在 update 函数期间更新 model.value:

type alias Model =
  { value : String
  , words : List String
  }

initialModel : Model
initialModel =
  { value = ""
  , words =
      [ "chair", "sofa", "table", "stove", "cabinet", "tv", "rug", "radio", "stereo" ]
  }

type Action
  = SetValue String

update action model =
  case action of
    SetValue value ->
      { model | value = value }

您还需要在输入该文本框时触发更新功能。您可以使用 on event attribute 执行此操作。监听 input 事件很常见,它为您提供了比 dividual 按键事件更多的信息:

inputField : Address Action -> Html
inputField address =
  input
    [ type' "text"
    , on "input" targetValue (Signal.message address << SetValue)
    ]
    [ ]

最后,您需要显示带有自动完成内容的 div:

autocomplete model =
  let
    matches =
      List.filter (startsWith model.value) model.words
  in
    div []
      [ div [] [ text <| "Autocomplete input: " ++ model.value ]
      , div [] [ text "Autocomplete matches: " ]
      , div [] <| List.map (\w -> div [] [ text w ]) matches
      ]

如果您决定变得更复杂并且需要外部资源来自动完成,您需要切换到 StartApp 而不是 StartApp.Simple,因为它支持效果和任务。

上面的代码片段依赖于对您最初发布的内容的一些其他更改,因此我发布了 gist with a working example that you can plug into http://elm-lang.org/try。希望这对您有所帮助!