您的位置:首页 > Web前端 > JavaScript

angular.js构建单页面购物车

2016-08-15 16:53 393 查看
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车</title>
<script src="../jquery.js"></script>
<script src="angular.js"></script>
<style>
*{
padding:0;
margin:0;
font-family: '微软雅黑';
}
.shop-items ul{
list-style: none;
width: 100%;
}
.shop-items ul li{
display: inline-block;
width: 10%;
text-align: center;
height: 30px;
line-height: 30px;
}
.shop-items ul li p{
border-bottom: 1px solid #ccc;
border-left: 1px solid #ccc;
}
.shop-items ul li:last-child p{
border-right: 1px solid #ccc;
}
.shop-items ul li input{
padding:2px 5px;
margin-bottom: 5px;
}

.shop-buy,.shop-total{
width: 50%;
margin-left: 30%;
margin-top:20px;
}
.shop-buy span{
display: inline-block;
width: 180px;
}
.shop-buy input{
padding:5px 8px;
}
.shop-total{
font-size: 25px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="shop-view" ng-app="shopping" ng-controller="myCtrl">
<div class="shop-items">             <!--ng-repeat写入数组中的数据-->
<ul>
<li ng-repeat="x in items">
<p>{{x.name}}</p>
<p>{{x.price}}/斤</p>
<p><input type="button" value="购买" ng-click="buy($index);"></p>
</li>
</ul>
</div>
<div class="shop-buy" ng-repeat="x in items">
<p>
<span>{{x.name}} : {{x.price|currency:"¥"}}</span><input type="button" value="-" ng-click="minus($index);"> <input type="text" ng-model="itemNum[$index]"> <input type="button" value="+" ng-click="add($index)"><span> 单品总价:{{x.price*itemNum[$index]|number:2}}元</span>
</p>
</div>
<div class="shop-total">
总价为:{{total|number:2}}元
</div>
</div>
<script>
var data=[
{"name":"苹果","price":"12.35"},
{"name":"香蕉","price":"8.9"},
{"name":"榴莲","price":"20.5"},
{"name":"电脑","price":"4000.9"},
{"name":"手机","price":"2089.5"},
{"name":"显示屏","price":"1223.35"},
{"name":"冰箱","price":"3451.9"},
{"name":"大金桔","price":"12.5"},
{"name":"切糕","price":"888.8"},
{"name":"大西瓜","price":"5.5"}
];
var app=angular.module("shopping",[]);
app.controller("myCtrl",function($scope){
$scope.items=data;
$scope.itemNum=[];
$scope.total=0;
var len=$scope.items.length;
for(var i=0;i<len;i++){
$scope.itemNum[i]=0;               //初始化ng-model中的值,另其为0
}
$scope.$watch("itemNum",function(){   //监听ng-model中的值的变化
$scope.getTotal();
},true)
$scope.buy=function(index){           //点击购买按钮时发生的事件
$scope.itemNum[index]++;
}
$scope.minus=function(index){         //减少数量
$scope.itemNum[index]--;
if($scope.itemNum[index]<=0){
$scope.itemNum[index]=0;
}
}
$scope.add=function(index){           //增加数量
$scope.itemNum[index]++;
}
$scope.getTotal=function(index){                         //重新计算总价
$scope.total=0;
for(var j=0;j<len;j++){
$scope.total=$scope.total+$scope.itemNum[j]*$scope.items[j].price;
}
return $scope.total;
}
})
</script>
</body>
</html>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: