【发布时间】:2017-11-20 21:55:54
【问题描述】:
我是 angularjs 的新手。我正在尝试创建一个购物车应用程序。到目前为止,一切都很顺利。但是,我需要将“数量”字段添加到“将商品添加到商店”部分。此数量应反映为下拉列表,其中包含给定项目的单位数量。
用户应该能够每次选择数量,金额应该是商品价格 * 商品数量 + 商品总数。我能做到吗?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1>Select item(s) and add to cart:</h1>
<div ng-repeat="item in items">
<label>
<input type="checkbox" ng-model="item.isSelected" />
<span>{{item.name}}</span>
<span>{{item.price}}</span>
</label>
</div>
<hr>
<p>Add items to shop</p>
Enter name: <input type="text" ng-model="newItemname" />
Enter price: <input type="text" ng-model="newItemprice" />
<button ng-click="addtoshop()">Add to shop</button>
<hr>
<h1>Add items to shopping cart</h1>
<button ng-click="addtocart((items | filter : { isSelected:true }))">Shop!</button>
<hr>
<p ng-model="amount">{{amount}}</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.items = [
{ name: "Bread", price: 20, isSelected: false },
{ name: "Butter", price: 25, isSelected: false },
{ name: "Jam", price: 30, isSelected: false },
];
$scope.addtoshop = function () {
var newitem = {};
newitem.name = $scope.newItemname;
newitem.price = $scope.newItemprice;
newitem.qty = $scope.newItemqty;
}
$scope.addtocart = function (index) {
alert("You chose " + index.length + " items.");
var p = 0, i;
for (i = 0; i < index.length; i++) {
p += parseInt(index[i].price);
}
alert("Shopping price: " + p);
$scope.amount = p;
};
});
</script>
</body>
</html>
【问题讨论】: