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

依然范特西╮ 提交于 2019-12-02 04:28:43

问题


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
    }];

}

回答1:


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>



回答2:


Try this:

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

and

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

jsfiddle




回答3:


Solution: Please Check this.This will resolve your problem Once you select from DROPDOWN the selected Object will be stored in customer. Then this customer object contains id as well as name

MISTAKE you have made is

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

Here ONLY item.id will be collected to customerId

If you want whole object then DO LIKE BELOW

    <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>


来源:https://stackoverflow.com/questions/29031394/how-to-assign-selected-options-text-to-another-model-while-using-ng-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!