Search code examples
angularjsangularjs-ng-modelangularjs-ng-optionsangularjs-select

how to make the user input appear in drop down menu in angularjs


I had created a dropdown menu with "other" option that enables the user to write an input then click on an add button to add it to the dropdown list. my problem is the user input is added to the dropdown menu but without being the "selected" option, the 'other' option still the selected one and I have to click on the menu to choose the user input.so the question is how to make the user input is the selected option when the user clicks on add button?

here is my html

<div class="col-sm-7" ng-class="{'has-error':orderWizard.material.$invalid && orderWizard.material.$dirty}">
    <select required id="form-control-1" name="material"
            class="form-control"
            ng-change="model.fetchPrice(); model.fetchRelatedNote('material')"
            ng-model="model.preferenceDTO.material"
            ng-options="material.name for material in model.productPreferences.material"
            data-placeholder="">
       <option ng-repeat="material in model.productPreferences.material">
         {{material.name}}
       </option>
       <option ng-if="model.checkIfCustomizedProduct" value="">
         NEW
       </option>
    </select>

    <div ng-if="model.preferenceDTO.material==material.name">
        <input class="form-control" type="text" 
               placeholder="please add new option"
               ng-model="newMaterial" />

        <div style="padding-top: 5px">
            <div ng-if="!newMaterial ==''">    
                <button type="button" class="btn btn- primary"
                        ng-click="model.addNewOption('material' ,newMaterial)" >
                  add
                </button>
            </div>
        </div>
    </div>
</div>

my controller.js

function addNewOption(prop, value) {
    model.productPreferences[prop].push({name: value})
    model.preferenceDTO[prop] = {name: value}
}

Solution

  • ERRONEOUS

    function addNewOption(prop, value) {
        model.productPreferences[prop].push({name: value})
        model.preferenceDTO[prop] = {name: value}
    }
    

    Instead:

    function addNewOption(prop, value) {
        var newOption = {name: value};
        model.productPreferences[prop].push(newOption);
        model.preferenceDTO[prop] = newOption;
    }
    

    The first case, with object literals, creates two new objects that have different reference values. The latter case creates only one new object which is shared between the selector list and the ng-model of the select element.