另一个 Angular 问题:
目的是使 #quantity 输入中输入的值与 Controller 中列出的商品价格相乘。
例如,如果价格为 99.00,用户想要的数量为 2,则 99 * 2 的结果将输出到 .total div 中。
我将如何创建这个?
我的 HTML 如下:
<input type="number" min="0" max="10" id="quantity" name="store-quantity" value='1'/>
<div class="total">
<!-- Total to be printed here -->
</div>
我的 store.controller.js 的一小段
angular.module('angularStoreApp')
.controller('StoreCtrl', function ($scope, $http) {
var item = [
{
name: 'Almond Toe Court Shoes, Patent Black',
price: 99.00,
category: 'Womens Footware',
stock: 5,
canPurchase: true,
images: [
"assets/images/yeoman.png",
"http://billypurvis.co.uk/wp-content/uploads/2015/06/ACTA.png"
]
},
最佳答案
我创建了一个plunker一个基于问题中最初的代码的示例,并进行了一些增强。
这是代码的相关部分:
<div ng-repeat="product in products" ng-show="product.canPurchase " class="item-panel">
<div class="pull-left full product-info">
<h1>{{product.name | limitTo: 20}}...</h1>
<h2 class="pull-left full">{{product.price | currency}}</h2>
<div ng-hide="{{product.stock <= 0}}">
<input class="pull-left voucher-input" placeholder="Voucher Code" />
<input type="number" ng-model="quantity" max="{{product.stock}}"/>
<input type="submit" value="Add to Cart" />
<div class="total">
Total:{{ product.price * quantity | currency }}
</div>
</div>
</div>
</div>
请注意,我首先将 ng-model="quantity"
添加到输入字段,提供 quantity
作为可访问的变量。由于 ng-repeat
的每次迭代都会为该 block 创建一个新范围,因此重复中的每个产品都会有一个 quantity
变量。
接下来,我将 max="{{product.stock}}"
添加到输入,以演示您可以将对象上的属性绑定(bind)到纯 HTML 元素项。如果您输入的数量大于 product.stock
,则 quantity
将设置为 NaN
。
最后我添加了实际计算总计:{{ 产品.价格 * 数量 |货币}}
。在这里,我使用了货币过滤器,它还确保如果quantity
为0
或NaN
,则显示为空白而不是NaN
.
关于javascript - 在 Angular.js 中使用预设变量添加用户输入的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30853285/