javascriptangularjsselectng-options

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.


Solution

  • 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 ;
    }