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

时间:2015-03-13 11:44:54

标签: javascript angularjs select model ng-options

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

以下示例和 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
    }];

}

3 个答案:

答案 0 :(得分:6)

试试这个:

<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

答案 1 :(得分:2)

请参阅下面的演示 在选择中,将模型更改为cutomer,在输入中使用customer.id customer.name

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

}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

<强>解决方案: 请检查一下。这将解决您的问题 从DROPDOWN中选择后,所选对象将存储在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>