如何在使用 ng-options 时将所选选项的文本分配给另一个模型?

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

我可以创建一个 select 标签并在其中放置数据。我可以将 select 的 selected 选项分配给一个模型,但不能将其文本分配给另一个模型。

下面是例子 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
    }];

}

请看下面的演示 在 select 中将您的模型更改为客户并在输入中使用 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>

试试这个:

<select ng-model="customer" ng-options="item.name for item in content">

<input disabled="disabled" type="text" ng-model="customer.id"/>
<input disabled="disabled" type="text" ng-model="customer.name"/>

jsfiddle

解法: 请检查 this.This 将解决您的问题 一旦您从 DROPDOWN 中 select,selected 对象将存储在 customer 中。然后这个 customer 对象包含 id 以及 name

你犯的错误是

     ng-model="customerId"  ng-options="item.id as item.name for item in content"

这里只有item.id会收集到customerId

如果你想要整个对象,请在下方点赞

    <div ng-app>
     <div ng-controller="DemoCtrl">
        <select ng-model="customer" ng-options="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>