本篇文章给大家分享的是有关使用Angular怎么计算购物车,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
实现过程:
一、使用任何语言创建一个服务端:
public class ShoppingCar
{
public string Title { get; set; }
public decimal UnitPrice { get; set; }
public int Count { get; set; }
}
public ActionResult GetCar()
{
List<ShoppingCar> cars = new List<ShoppingCar>
{
new ShoppingCar { Title="苹果",Count=1,UnitPrice=2.5m},
new ShoppingCar { Title="香蕉",Count=3,UnitPrice=1.5m},
new ShoppingCar { Title="苦瓜",Count=1,UnitPrice=3.5m},
new ShoppingCar { Title="黄瓜",Count=3,UnitPrice=2.2m}
};
return Json(cars,JsonRequestBehavior.AllowGet);
}
public ActionResult AddCar(List<ShoppingCar> car)
{
return Json("ok", JsonRequestBehavior.AllowGet);
}
二、前台实现:
<div ng-app="DemoApp" ng-controller='CartController'>
<table class="table table-striped">
<thead>
<tr>
<td>标题</td>
<td>单价</td>
<td>数量</td>
<td>小计</td>
<td>删除</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in ShoppingCar">
<td>{{item.Title}}</td>
<td>{{item.UnitPrice}}</td>
<td>
<input type="text" ng-cloak ng-model="item.Count" >
<button my-adds ng-click="UpdateCar(item.Title,1)" ng-class="{cursors:true}">+</button>
<button my-minus ng-click="UpdateCar(item.Title,-1)" ng-class="{cursors:true}">-</button>
</td>
<td>{{item.Count*item.UnitPrice | number:2}}</td>
<td><button my-minus ng-click="UpdateCar(item.Title,-100)" ng-class="{cursors:true}">删</button></td>
</tr>
</tbody>
</table>
<p ng-init=0>总价格:{{ total | number:2}}</p>
<button type="button" ng-click="submit()">提交</button>
</div>
三、Angular部分
var app = angular.module('DemoApp', []);
app.controller('CartController', ['$scope', '$http', function ($scope, $http) {
$scope.ShoppingCar = {}
var GetCar = function () {
$http.get('/Employee/GetCar')
.success(function (response) {
$scope.ShoppingCar = response;
GetTotal();
});
}
$scope.total = 0;
var GetTotal = function () {
for (var i = 0; i < $scope.ShoppingCar.length; i++) {
var item = $scope.ShoppingCar[i];
$scope.total += item.Count * item.UnitPrice;
}
}
$scope.UpdateCar = function (title, count) {
for (var i = 0; i < $scope.ShoppingCar.length; i++) {
var item = $scope.ShoppingCar[i];
if (item.Title == title) {
item.Count = item.Count + count;//这里可以增加上下限制
if (item.Count < 0) {
$scope.ShoppingCar.splice(i, 1);
}
}
}
GetTotal();
}
$scope.submit = function () {
$http.post('/Employee/AddCar', $scope.ShoppingCar)
.success(function (response) {
alert(response);
});
}
GetCar();
}]);
以上就是使用Angular怎么计算购物车,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。