如何访问后续各行中的第一个数量和价格值:
在这种情况下,“选择”是由一些单选按钮设置的变量。
<tr ng-repeat="(qty, price) in product.sizes[selection]">
<td><input type="radio"> <% qty %></td>
<td><% price %></td>
<td>You save (actual calc more complex) {{price - FIRSTROWPRICE}}</td>
</tr>
我可以通过使用 $first/ng-if 来阻止最后一行进行数学运算,所以没有问题。
这是数据:
{
"name": "The product",
"sizes": {
"2x2": { "100": "55", "200": "80", "300": "95"},
"3x3": { "100": "155", "200": "180", "300": "195"}
}
}
并且使用一些单选按钮选择“选择”参数:
<form>
<div class="radio" ng-repeat="(size, data) in product.sizes">
<label>
<input type="radio" value="{{ size }}" ng-model="$parent.selection"> {{ size }}
</label>
</div>
</form>
最佳答案
这是一种解决方案:
首先,您需要在作用域上有一个函数来跟踪哪个键先出现:
// in controller
$scope.setFirst(key, isFirst) {
if(isFirst) { $scope.first = key; }
};
现在,在您看来,您应该这样做:
<tr ng-repeat="(qty, price) in product.sizes[selection]" ng-init="setFirst(qty,$first)">
<td><input type="radio"> <% qty %></td>
<td><% price %></td>
<td>You save (actual calc more complex) {{price - product.sizes[first]}}</td>
</tr>
或者,您可能希望通过仅存储第一个价格来减少计算次数:
$scope.setFirstPrice(price, isFirst) {
if(isFirst) { $scope.firstPrice = price; }
}
和
<tr ng-repeat="(qty, price) in product.sizes[selection]" ng-init="setFirstPrice(price,$first)">
<td><input type="radio"> <% qty %></td>
<td><% price %></td>
<td>You save (actual calc more complex) {{price - product.sizes[first]}}</td>
</tr>
您的选择取决于您的需求。关键步骤是使用 Controller 上的函数来跟踪首先呈现的价格。
请注意:
在 JavaScript 中, HashMap 对象中的参数顺序无法保证!浏览器可能会选择以不同的顺序输出项目,因此您可能并不总是首先获得预期的项目。如果顺序确实很重要,请考虑将数据结构重新排列为对象数组,例如:
"sizes": {
"2x2": [{ price:"100", qty:"55"}, {price:"200", qty:"80"}, {price:"300", qty:"95"}],
// etc
}
如果大小
的顺序很重要,您将希望对该对象执行相同的操作。
这可能没问题,只需确保在您想要支持的所有浏览器中进行彻底测试即可。
关于javascript - 访问 ng-repeat 的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18478856/