Search code examples
javascriptangularjsselectmodelng-options

How to assign selected option's text to another model while using ng-options?


I can create a select tag and place data inside it. I can assign that select's selected option to a model but can't assign its text to another model.

Here is example below and jsFiddle link

html:

<div ng-app>
  <div ng-controller="DemoCtrl">
      <select ng-model="customerId" ng-options="item.id as item.name for item in content" ng-change="customerName = item.name">
</select>
      <br/>
      <input disabled="disabled" type="text" ng-model="customerId"/>
      <input disabled="disabled" type="text" ng-model="customerName"/>
      <!-- i'm trying to get customer name and assign that on to my model -->
  </div>
</div>

js:

function DemoCtrl($scope) {
  $scope.content = [
    {
        name: "Bireysel",
        id: 1
    },
    {
        name: "Kurumsal",
        id: 2
    },
    {
        name: "Bireysel & Kurumsal",
        id: 3
    }];

}

Solution

  • Please see demo below In select change your model to cutomer and in inputs use customer.id customer.name

    function DemoCtrl($scope) {
      $scope.content = [{
        name: "Bireysel",
        id: 1
      }, {
        name: "Kurumsal",
        id: 2
      }, {
        name: "Bireysel & Kurumsal",
        id: 3
      }];
    
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app>
      <div ng-controller="DemoCtrl">
        <select ng-model="customer" ng-options="item as item.name for item in content" ng-change="customerName = item.name">
        </select>
    
        <br/>
        <input disabled="disabled" type="text" ng-model="customer.id" />
        <input disabled="disabled" type="text" ng-model="customer.name" />
      </div>
    </div>