简体   繁体   English

将ng-options值和标签绑定到ng-model

[英]Bind ng-options value and label to ng-model

I'm using ng-options to generate a select tag whose options are locations. 我正在使用ng-options生成一个选项标签,其选项是位置。 The labels are the location names, and the values are the location ID (in database). 标签是位置名称,值是位置ID(在数据库中)。

I've bound the value (location ID) to an ng-model attribute, but I'd also like to bind the label (location name) to a different ng-model attribute. 我已将值(位置ID)绑定到ng-model属性,但我还想将标签(位置名称)绑定到不同的ng-model属性。 (I need to separate the id field since this will be POSTed to a server that expects this particular attribute.) What's the best way to do this in Angular? (我需要将id字段分开,因为这将被POST到需要此特定属性的服务器。)在Angular中执行此操作的最佳方法是什么?

My code: 我的代码:

<div ng-app="app"><div ng-controller="edit">
  <select ng-model="purchase.pickUpLocationId" ng-options="loc.id as loc.name for loc in purchase.availableLocations"></select>

  <!-- This is the model not yet bound: -->
  <p>You have selected {{ purchase.pickUpLocationName }}</p>

</div></div>

var app = angular.module('app', []);

app.controller('edit', ['$scope', function($scope) {
    $scope.purchase = {
        pickUpLocationId: 30,
        availableLocations: [
            {id: 20, name: "Charleston, SC"},
            {id: 30, name: "Atlanta, GA"},
            {id: 40, name: "Richmond, VA"},
        ]
    };
}]);

You can change to the following and bind to the entire object. 您可以更改为以下内容并绑定到整个对象。 You'll still have access to id later on for whatever you wish to do with it 无论你想用它做什么,你以后仍然可以访问id

<select ng-model="selected" ng-options="loc as loc.name for loc in purchase.availableLocations"></select>

<p>You have selected {{ selected.name }}</p>
<p>You havd id too! {{ selected.id }}</p>

JSFiddle Link JSFiddle链接

My suggestion is to model as a hash first 我的建议是首先建模为哈希

{
   "20": "Charleston, SC",
   "30": "Atlanta, GA"
}

and then use {{availableLocations[purchase.pickUpLocationId]}} 然后使用{{availableLocations[purchase.pickUpLocationId]}}

and make ng-options as 并使ng-options为

<select ng-model="purchase.pickUpLocationId" ng-options="id as label for (id, label) in purchase.availableLocations"></select>

Updated scniro answer 更新了scniro答案

<div ng-app="app">
<div ng-controller="ctrl">
     <select ng-model="selected" ng-options="opt as opt.language for opt in tableResult.locales"></select>        
     <p>You have selected {{ selected.language }}</p>
     <p>You havd id too! {{ selected.localeId }}</p>
     <p>
     </p>
     <input type="text" value="{{selected.localeId}} : {{selected.language}}" style="width:50%;"/>

</div>

JSFIDDLE -Bind ng options value and label JSFIDDLE - 绑定选项值和标签

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM