来自一个 ng 的多个 ng-model
Multiple ng-model from one ng
亲爱的,我正在创建一个复选框,它将显示多个项目的名称及其价格,用户可以选择 he/she 想要的。在 ng-model 中,我需要商品名称和价格。这是我找到的一个示例代码。
<div class="checkbox" ng-repeat="item in items">
<label>
<input ng-model="data[item.name + '||' + item.price]" type="checkbox" id="{{item.id}}">
{{item.name}} with {{item.price | currency}}
</label>
</div>
后来使用字符串拆分器来获取值。有什么办法可以使用两个不同的 ng-model 获得 item.name 和 item.price 吗?
不,你不能对同一个元素使用 2 个 ng-models,这也没有任何意义。
只需将 ng-model
设置为项目上的 属性 说 selected
<input ng-model="item.selected" type="checkbox" id="{{item.id}}">
并且由于项目对象本身有价格和名称,您可以轻松过滤掉项目 selected
及其各自的名称和价格。
例如:
var selectedItems = $scope.items.filter(function(itm){return itm.selected});
如果你想将 ngmodel
设置为 id 和值作为项目属性(你在问题中的方式)你也可以使用 ng-true-value
(虽然我认为以前的方法应该只是够了)。
<input ng-model="data[item.id]" ng-true-value="{{item.name + '||' + item.price}}" type="checkbox" id="{{item.id}}">
亲爱的,我正在创建一个复选框,它将显示多个项目的名称及其价格,用户可以选择 he/she 想要的。在 ng-model 中,我需要商品名称和价格。这是我找到的一个示例代码。
<div class="checkbox" ng-repeat="item in items">
<label>
<input ng-model="data[item.name + '||' + item.price]" type="checkbox" id="{{item.id}}">
{{item.name}} with {{item.price | currency}}
</label>
</div>
后来使用字符串拆分器来获取值。有什么办法可以使用两个不同的 ng-model 获得 item.name 和 item.price 吗?
不,你不能对同一个元素使用 2 个 ng-models,这也没有任何意义。
只需将 ng-model
设置为项目上的 属性 说 selected
<input ng-model="item.selected" type="checkbox" id="{{item.id}}">
并且由于项目对象本身有价格和名称,您可以轻松过滤掉项目 selected
及其各自的名称和价格。
例如:
var selectedItems = $scope.items.filter(function(itm){return itm.selected});
如果你想将 ngmodel
设置为 id 和值作为项目属性(你在问题中的方式)你也可以使用 ng-true-value
(虽然我认为以前的方法应该只是够了)。
<input ng-model="data[item.id]" ng-true-value="{{item.name + '||' + item.price}}" type="checkbox" id="{{item.id}}">