smartmouse
smartmouse

Reputation: 14404

How to add custom option to ng-options output?

i created a select in a table that get some email address from a list. Here is the code:

<td>
    <select ng-init="selectedEmail = selectedEmail ? selectedEmail : emails[0]" class="form-control" ng-model="selectedEmail" ng-options="item as item.dest for item in emails"></select>
</td>

I would add an additional option that would be a custom option for the final users. If i add <option> within <select> it is being overwritten by Angular ng-options

<td>
    <select ng-init="selectedEmail = selectedEmail ? selectedEmail : emails[0]" class="form-control" ng-model="selectedEmail" ng-options="item as item.dest for item in emails">
        <option value="custom">Custom</option>
    </select>
</td>

How can i add a custom option?

My purpose is to add a "custom" choice for the users: if they select that option they can write down their own choice, a custom text.

Upvotes: 3

Views: 6413

Answers (3)

Malkus
Malkus

Reputation: 3726

There are several ways to solve this problem. If you want to continue using ng-options you can use a function.

HTML

<td>
    <select 
        ng-init="selectedEmail = selectedEmail ? selectedEmail : emails[0]"
        class="form-control" 
        ng-model="selectedEmail" 
        ng-options="item as item.dest for item in BuildList()"></select>
</td>

<input type="text" placeholder="Enter Custom Option" ng-model="customText" />

Controller Function for BuildList

$scope.BuildList = function() {

    if(!$scope.customText) {
       return $scope.emails;
    }
    var newList = angular.copy($scope.emails);
    newList.push({someobjectbuildUsingCustom});

    return newList ;
}

Upvotes: 1

Jax
Jax

Reputation: 1843

You can do as per below:

<div ng-controller="TestController">
  {{sel}}
  <select ng-model="sel" ng-options="d.value as d.label for d in data">
    <option value="">any</option>
  </select>
</div>

see this fiddle as well

Upvotes: 2

Digix
Digix

Reputation: 64

You can use this syntax :

<select>
    <option ng-repeat="(key, value) in emails" value="{{key}}">{{value}}</option>
    <option ... custom option ...>...</option>
</select>

Upvotes: -2

Related Questions