How do I add leading spaces into the <select>
options using Angular ng-options?
<div ng-controller="MyCntrl">
Static values (works)
<select>
<option value="black">black</option>
<option value="white"> white</option>
<option value="red"> red</option>
<option value="blue"> blue</option>
<option value="yellow"> yellow</option>
</select>
Values from JS using angular (only the first-default works)
<select ng-model="color" ng-options="c.name for c in colors">
<option value=""> default</option>
</select>
</div>
JS:
angular.module("myApp", []).
controller("MyCntrl", ['$scope', function ($scope) {
$scope.colors = [{
name: 'black',
shade: 'dark'
}, {
name: ' white',
shade: 'light'
}, {
name: ' red',
shade: 'dark'
}, {
name: ' blue',
shade: 'dark'
}, {
name: ' yellow', // spaces here
shade: 'light'
}];
}]);
you can format the option text:
<select ng-model="color" ng-options="(' '+c.name) for c in colors">
<option value=""> default</option>
</select>
EDIT
If you want to generate the
dynamically it is a little bit more complicated. Suppose you have a function in your controller that knows how many
you want to add, then you can write this function like this:
$scope.addSpaces= function(color){
var count = 1;// put your logic here
var result = "";
for(var i=0; i<count; i++){
result+= String.fromCharCode(160);
}
return result;
};
in your html it will be:
<select ng-model="color" ng-options="(addSpaces(c)+c.name) for c in colors">
<option value=""> default</option>
</select>
This works because we concatenate the unicode character for
(e.g.  
) in our string and not the entity, so there is nothing to escape for the element.text()
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With