Update value of an input text when an option is selected with angularjs

jjprz picture jjprz · May 23, 2016 · Viewed 10.8k times · Source

I have my controller in angularjs with a array

app.controller('player', function($scope) {
    $scope.players = [
        {
            "id":3,
            "name":"Nadal",
        },
        {
            "id":4,
            "name":"Federer"
        }
    ]
});

In my HTML I have HTML with a dropdown and a textbox.

 <html ng-app="pdl">  
    <body ng-controller="player">  
        <input type="text" id="name" value=""/>
        <select name="id">  
            <option ng-repeat="player in players" value="{{player.id}}">{{player.id}}</option>  
        </select>  
    </body>  
 </html>  

I want to update the input with a 'name' when I choose an option from the dropdown

Answer

dfsq picture dfsq · May 23, 2016

Bind both select and input to the same ngModel:

angular.module('pdl', []).controller('player', function($scope) {
  $scope.players = [{
    "id": 3,
    "name": "Nadal",
  }, {
    "id": 4,
    "name": "Federer"
  }]
});
<script src="https://code.angularjs.org/1.5.5/angular.min.js"></script>

<div ng-app="pdl" ng-controller="player">
  <input type="text" ng-model="player.name" />
  <select ng-model="player" ng-options="player as player.name for player in players">
  </select>
</div>

And use ngOptions for selectbox.