【问题标题】:Elm filter a list with input StringElm 过滤带有输入字符串的列表
【发布时间】:2020-06-21 02:50:28
【问题描述】:

我有模特

   type alias Model =
    { 
      url : String
    , devices : List Device
    , input : String
    , isFilter : Bool
    , deviceSuggestion : Maybe Device
    }

type alias Device =
    { 
      status : String
    , license_plate : String
    , device_id : String
    }

这是我更新数据的方式,但我不知道在搜索框中输入内容后如何过滤

update msg model =
case msg of
    GotResult result ->
        case result of
            Ok devices ->
                ( { model | devices = devices }, portDevice devices )

            Err devices ->
                ( { model | error = Just "Error" }, Cmd.none )

    Tick _ ->
        ( model, fetchUrl )

    InputChange newInput ->
         ( { model | input = newInput //function filter here?}, Cmd.none)
        
    SearchFunction ->
        ({ model | input = "" }, toJS model.input)

这是我的渲染视图

renderPosts : Model -> Html Msg
    renderPosts model =
    div []
        [ h3 [] [ text "Filter List" ] ,
        , input [ type_ "text"
                , placeholder "Searching for devices"
                , onInput InputChange
                , value model.input
                , id "inputDevices"
                ] []
         --, checkListFunction model //check and filter list function here as well?
         , button [ onClick SearchFunction , id "searchDevice"] [ text "Search" ]
         ,
            div []
            ([ text "Device List" ] ++ List.map (\device -> renderPost device) model.devices) //display function
            ]

我希望输出就像我在搜索框中输入 1234 时一样,然后它会使用设备列表中的 license_plate 检测并过滤以下列表。

**我尝试了 list.filter 但它允许比较列表列出。 **我试过 String.contains 但我需要 2 个字符串。因为输入框是字符串,license_plate 是列表,所以报错

感谢您的帮助... https://www.w3schools.com/howto/howto_js_filter_lists.asp

【问题讨论】:

    标签: string list filter compare elm


    【解决方案1】:

    下面是使用filteredDevices 绑定修改renderPosts 函数的示例,展示了如何应用过滤器:

    renderPosts : Model -> Html Msg
    renderPosts model =
        let
            filteredDevices =
                List.filter (\device => String.contains model.input device.license_plate) model.devices
        in
        div []
            [ h3 [] [ text "Filter List" ] ,
                ...
                div []
                ([ text "Device List" ] ++ List.map (\device -> renderPost device) filteredDevices)
                ]
    

    【讨论】:

    • 感谢@glennsl 的回复,但我仍然收到错误^^^^^^^^^^^^^^此filteredDevices 值为a:List { a | license_plate : 字符串 } -> 列表 { 一个 | license_plate : String }但map 需要第二个参数为:List Device
    • 哦,抱歉,我忘记了指定要过滤的列表的参数!已在答案中修复。
    • 不过也可能有其他错误。我(显然)没有通过编译器或任何东西运行它。这只是为了让您了解如何做。
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 2022-01-16
    • 2021-11-15
    • 2021-11-23
    • 2020-05-21
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    相关资源
    最近更新 更多