Parvindra Singh
Parvindra Singh

Reputation: 53

How to pass a Comma seperated String to select options in Angular js

I have this Json:

        {
                "field_id": "4otBG",
                "label": "Fullness",
                "type": "dropdown",
                "props": {
                    "req": "true",
                    "options": "Empty-ish, Plenty of Seats, Few Seats, Standing, Packed Like Sardines"
                }
            }

How to pass the Options to an selection option , because it is a comma separated string Please help me..

Upvotes: 0

Views: 4057

Answers (2)

Jon Jaques
Jon Jaques

Reputation: 4410

The angular way would be to use a filter. Note you're not supposed to use $ prefix, but since this is such a general purpose filter I thought it was appropriate. Feel free to rename.

.filter('$split', function() {
  return function(val, splitter) {
    if (!splitter) { splitter = ','; }
    return (val && val.length) ? val.split(splitter) : [];
  }
});

Use it like so.

<select ng-options="val for val in props.options | $split" />

You can even pass an additional param if you have data that is delimited by a different character.

<select ng-options="val for val in props.options | $split:'|'" />

Upvotes: 2

A.B
A.B

Reputation: 20445

Assuming that you have got you data in $scope.data

$scope.optionsplit =  $scope.data.props.options.split(',');

In view

<select name="yourinput">
   <option ng-repeat="o in optionsplit" value="{{o}}">{{o}}</option>
<select>

Or with ng-options

<select ng-options="o for o in optionsplit">

</select>

or you can make a filter for it

filter('commaspliter', function() {
    return function(input) {
    return input.split(',');
    } 
  });

In view

<select name="yourinput">
<option ng-repeat="o in data.props.options | commaspliter"></option>
 </select>

Upvotes: 5

Related Questions