Search code examples
htmlangularjsdrop-down-menuangularjs-scope

How to get selected value from a select/dropdown using a button, with AngularJS?


I have a select with some values. A user chooses the value that he wants and then uses a button to add it to another list. However, I'm having trouble getting the currently selected value from the select. Here's my code:

add-contract.html

<div class="col-md-5">
    <label class="child-label" for="existing-phases">Existing:&nbsp;&nbsp;</label>
    <select class="form-control" id="existing-phases" >
         <option disabled selected value>-- select an option --</option>
         <option ng-repeat="p in existingPhases" value="{{p.ID}}">{{ p.Name }}</option>
    </select>
    <a class="btn btn-primary add-contract-button pull-right" ng-click="addPhase()">+</a>
</div>

I don't have access in my button to the scope that is being used on the select. How can I get the selected element?


Solution

  • You can bind the value of the select to your controller by using

    ng-model

    as shown in the docs.

    To share your value amongst your controller, you can:

    1. Use a service
    2. Share the variable throught the $scope.$parent access, if you have a parent-child scope Hierarchy.