【发布时间】:2018-05-17 06:27:36
【问题描述】:
假设我有一个对象列表,例如 -
var configs = [{
id: "1",
name: "config1"
},
{
id: "2",
name: "config2"
}
];
我使用以下内容搜索配置列表并将所选配置绑定到另一个名为changed_config的变量。
<table style="width:900px;">
<tr>
<th style="width:500px; margin:50px">Config Name</th>
<th style="width:150px;">Config Value</th>
</tr>
<tr ng-repeat="changed_config in changed_configs">
<td>
<input type="text" class="form-control" ng-model="changed_config.id" list="names">
<datalist id="names">
<option ng-repeat="option in configs | filter:search | limitTo:30" ng-value="option.name"> {{option.name}}
</option>
</datalist>
<td>
<input type="text" class="form-control" ng-model="changed_config.value">
</td>
</tr>
</table>
<div class="row">
<button type="button" id="add-reward-grp-btn" ng-click="addConfig()"
class="btn btn-primary">Add Config
</button>
</div>
控制器代码(不完整代码,只是相关的sn-ps):
var app = angular.module("drs_scheduler_app", []);
app.controller("CreateSchedulerJob", function ($scope, $http) {
$scope.changed_configs = [];
$scope.configs = [{
id: "1",
name: "config1"
},
{
id: "2",
name: "config2"
}
];
$scope.addConfig = function () {
var config = {
"id": "",
"value": ""
};
$scope.changed_configs.push(config);
console.log(config);
console.log(JSON.stringify($scope.changed_configs));
}
}
当前代码显示并将所选配置的name 绑定到changed_config 变量。但我需要将id 绑定到changed_config 变量,并将name 显示在html 中。
如果我将 <option> 更改为使用 id,则将显示 id。
如何将一个属性绑定到一个变量,但在 html 中显示另一个?
【问题讨论】:
-
将
ng-value="option.name"更改为ng-value="option.id" -
我想我在这里遗漏了一些东西。为什么不能使用 ng-value="option.id" ?
-
但这将在输入字段中显示
id。我需要在字段中显示name,但将id绑定到变量 -
然后你需要设置 ng-value="option" 并用它做任何事情
-
你说的是哪个输入框?
标签: javascript angularjs angular angular-ngmodel angularjs-ng-model