2

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

dfsq
  • 191,768
  • 25
  • 236
  • 258
jjprz
  • 55
  • 1
  • 2
  • 8

2 Answers2

3

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

The solution above works, but breaks if you want to amend the input value after its been written. In the example above change the word Nadal and the select is changed also as they are bound to the same value.

If want to amend the value of the input and you don't want to bind to the same ngModel, you could use ng-change on the select, and pass it the value you want to display in the input.

In this example I insert the "ng-change" statement on the select...

ng-change="change(model.action)"

and in the controller I update the scope for the input

    $scope.change = function (str) {
        $scope.model.action = str;
    };

Every time you update the select the input will update too, but you can amend the input value without touching the select as they are bound differently.

Darren Street
  • 1,652
  • 17
  • 21