Allow manually entered text in ui-select

后端 未结 5 592
北海茫月
北海茫月 2020-12-05 13:24

I am using a select box from ui-select. All is working fine, but I want to allow manually entered text and do not want to restrict the user from the values available in the

5条回答
  •  被撕碎了的回忆
    2020-12-05 13:39

    I use keyup to add a new option represents the text entered. With this approach, if user press enter, they can select what they have input so far (the default active item is the first item).

    This supports both cases when the data list contains plain text or object (attribute value-prop is required).

    Directive:

    commonApp.directive("uiSelectFreeText", function () {
        return {
            restrict: "A",
            require: "uiSelect",
            link: function (scope, element, attrs, $select) {
                var searchInput = element.querySelectorAll("input.ui-select-search");
    
                if (searchInput.length !== 1) {
                    console.log("Error! Input not found.");
                    return;
                }
    
                searchInput.on("keyup", function () {
                    var valueProp = attrs["valueProp"];
                    var addNewObjOption = function () {
                        // add new item represent free text option
                        var newOption = { isFreeText: true };
                        newOption[valueProp] = $select.search;
                        $select.items.unshift(newOption);
                    };
    
                    if ($select.items.length > 0) {
                        var firstItem = $select.items[0];
    
                        if (valueProp) {
                            // items is list of Object
                            if (firstItem.isFreeText) {
                                firstItem[valueProp] = $select.search;
                            } else {
                                addNewObjOption();
                            }
                        } else {
                            // items is list of string
                            if (firstItem === $select.search) {
                                return;
                            } else {
                                $select.items.push($select.search);
                            }
                        }
                    } else {
                        if (valueProp) {
                            addNewObjOption();
                        } else {
                            // items is list of string
                            $select.items.push($select.search);
                        }
                    }
                });
            }
        };
    });
    

    HTML:

    
    
    

提交回复
热议问题