Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add space to <select> with ng-options

Tags:

angularjs

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">&nbsp;white</option>
        <option value="red">&nbsp;&nbsp;red</option>
        <option value="blue">&nbsp;&nbsp;&nbsp;blue</option>
        <option value="yellow">&nbsp;&nbsp;&nbsp;&nbsp;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="">&nbsp;&nbsp;&nbsp;default</option>
    </select>
</div>

JS:

    angular.module("myApp", []).
    controller("MyCntrl", ['$scope', function ($scope) {
        $scope.colors = [{
            name: 'black',
            shade: 'dark'
        }, {
            name: '&nbsp;white',
            shade: 'light'
        }, {
            name: '&nbsp;&nbsp;red',
            shade: 'dark'
        }, {
            name: '&nbsp;&nbsp;&nbsp;blue',
            shade: 'dark'
        }, {
            name: '       yellow', // spaces here
            shade: 'light'
        }];
    }]);
like image 288
przno Avatar asked Jan 23 '14 09:01

przno


1 Answers

you can format the option text:

<select ng-model="color" ng-options="('&nbsp;'+c.name) for c in colors">
    <option value="">&nbsp;default</option>
</select>

EDIT

If you want to generate the &nbsp; dynamically it is a little bit more complicated. Suppose you have a function in your controller that knows how many &nbsp; 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="">&nbsp;default</option>
</select>

This works because we concatenate the unicode character for &nbsp; (e.g. &#160;) in our string and not the entity, so there is nothing to escape for the element.text() function.

like image 185
michael Avatar answered Nov 03 '22 00:11

michael