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
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: