我使用ng-options
生成其选项为位置的选择标记。标签是位置名称,值是位置ID(在数据库中)。
我已将值(位置ID)绑定到ng-model
属性,但我还想将标签(位置名称)绑定到不同的ng-model
属性。 (我需要将id
字段分开,因为这将被发布到需要此特定属性的服务器。)在Angular中执行此操作的最佳方法是什么?
我的代码:
<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"},
]
};
}]);
答案 0 :(得分:9)
您可以更改为以下内容并绑定到整个对象。您稍后仍可以访问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>
答案 1 :(得分:3)
我的建议是先建模为哈希
{
"20": "Charleston, SC",
"30": "Atlanta, GA"
}
然后使用{{availableLocations[purchase.pickUpLocationId]}}
并将ng-options设为
<select ng-model="purchase.pickUpLocationId" ng-options="id as label for (id, label) in purchase.availableLocations"></select>
答案 2 :(得分:0)
更新了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>