We all must have faced a challenge of formatting select options, as the specification says the content of option can only be plain text.
Specification: http://www.w3.org/TR/html-markup/option.html
Thus we might use jQuery widgets for a custom select.
Recently I faced a challenge working with select/drop-downs that I had to show a tip/help text to the extreme right in an option. Just for adding few spaces, using a custom select directive or widget didn’t seem to be a good option.
This article talks about making use of angular’s binding mechanism to get a value option with calculated number of spaces added between the option-text & help text.
First thing is to set a limit to the number of characters you can have in the option text, and rest of the logic goes like this:
Add this helper function & a constant to your controller:
const CHAR_LIMIT = 100;
$scope.getComputedText = function(text, help){
var spaces = “”;
var spacesNeeded = CHAR_LIMIT – (text.length + help.length);
for (var idx = 0; idx < spacesNeeded; idx++){
spaces += String.fromCharCode(160);
}
return text + spaces + help;
}
Generate your select mark-up like:
<select>
<option ng-repeat=”currentOption in availableOptions”>
{{getComputedText(currentOption.text, currentOption.helpText)}}
</option>
</select>
PS: Doing this called for writing a post, as adding didn’t work. The option value will show s as it is in drop-down, after adding & nbsp;s dynamically based on text length.
String.fromCharCode(160) does the trick.