我有一点问题,我有一个为我提供产品的API,每个产品都有多个选项,如下所示:
[
{
"name": "Product 1",
"options": [
{
"name": "Product 1 all options",
"price": 2000
}, {
"name": "Product 1 no option",
"price": 1400
}
]
}, {
"name": "Product 2",
"options": [
{
"name": "Product 2 all options",
"price": 3000
}, {
"name": "Product 2 no option",
"price": 1900
}
]
}];
现在我这样呈现:
<tbody>
<tr ng-repeat="product in products">
<td>{{ product.name }}</td>
<td>
<select class="form-control">
<option
ng-repeat="option in product.options"
data-price="{{ option.price }}">{{ option.name }}</option>
</select>
</td>
<td>HERE I WANT TO DISPLAY THE SELECTED option.price +/- VAT</td>
</tr>
</tbody>
现在您可能已经注意到,<select>
标记本身位于ng-repeat
内,因此可以无限重复,具体取决于我拥有的产品数量;我无法将select
绑定到任何ng-model
,因为我可能会意外地将多个<select>
绑定到同一模型。
现在,对于每个<select>
,我必须在第三个<td>
中显示与所选选项对应的增值税+/-增值税。有没有办法用angularjs做到这一点?我不想简单地使用JS / jQuery。
答案 0 :(得分:1)
您可以使用产品变量作为选择的模型。当值改变时,它也将在select之外更新。
一个例子是:
app.controller('MainCtrl', function($scope) {
$scope.products = ['a', 'b', 'c', 'd'];
});
<body ng-controller="MainCtrl">
<div ng-repeat="product in products">
<input ng-model="product">
<div>{{product}}</div>
</div>
</body>
你可以找到一个有效的plnkr here。
使用您的数据的工作示例。它正在您的产品中创建一个名为 selectedPrice 的新字段,以存储所选选项。
app.controller('MainCtrl', function($scope) {
$scope.products = [{
"name": "Product 1",
"options": [{
"name": "Product 1 all options",
"price": 2000
}, {
"name": "Product 1 no option",
"price": 1400
}]
}, {
"name": "Product 2",
"options": [{
"name": "Product 2 all options",
"price": 3000
}, {
"name": "Product 2 no option",
"price": 1900
}]
}];
});
<table>
<tbody>
<tr ng-repeat="product in products">
<td>{{ product.name }}</td>
<td>
<select class="form-control" ng-model="product.selectedPrice">
<option ng-repeat="option in product.options" value="{{ option.price }}">{{ option.name }}</option>
</select>
</td>
<td>{{product.selectedPrice}}</td>
</tr>
</tbody>
</table>
可以找到here的工作示例。
答案 1 :(得分:1)
@toskv的替代方案,您也可以完全避免选项标记。
<tr ng-repeat="product in products">
<td>{{ product.name }}</td>
<td>
<select class="form-control" ng-model="product.selectedPrice" ng-options="option.price as option.name for option in product.options track by option.name">
</select>
</td>
<td>{{product.selectedPrice}}</td>
</tr>
请参阅this