angular初始用——简易购物车

时间:2022-07-02 07:26:48
 <html>
<head>
<meta charset="utf-8">
<script src="js/angular.js"></script>
<script src="js/mult_app.js"></script>
<link rel="stylesheet" href="css/bootstrap.css">
<style>
.nested {
border: 1px solid red;
margin-left: 2em;
padding: 1em;
}
</style>
</head>
<body ng-app="MyApp">
//angularjs版本的多个购物车
<div ng-controller="MyCar">
<ul ng-repeat="item in carList">
<li>名字{{item.name}} 数量&nbsp;&nbsp;<span ng-click="minus(item.index)">-</span>&nbsp;&nbsp;{{item.num}}&nbsp;&nbsp;<span ng-click="plus(item.index)">+</span> 价格{{item.price}}
<span ng-click="remove(item.index)">删除</span>
</li>
</ul>
总价 {{totalPrice}}
</div>
</body>
</html>
 var app = angular.module("MyApp", []);

 var carList = [{
name: "牛奶",
price: 20,
num: 1
},{
name: "鮮花",
price: 5,
num: 1
},{
name: "水果",
price: 10,
num: 1
},{
name: "鸡蛋",
price: 2,
num: 1
}];
function wrapData(data){
for(var i =0; i< data.length; i++) {
data[i].index = i;
data[i].initPrice = data[i].price;
}
}
function store(namespace, data) {
if(arguments.length > 1) {
localStorage.setItem(namespace, JSON.stringify(data));
}else {
var obj = localStorage.getItem(namespace);
return (obj && JSON.parse(obj)) || null
}
}
function getTotalPrice(data){
var totalPrice = 0;
for(var i =0; i< data.length; i++) {
totalPrice+= data[i].num * data[i].initPrice
}
return totalPrice;
}
wrapData(carList); app.controller("MyCar", function($scope) {
//模块作用域
$scope.carList = store('mycar') || carList;
$scope.totalPrice = getTotalPrice(carList);
$scope.$watch("carList", function(newvalue, oldvalue){
$scope.totalPrice = getTotalPrice($scope.carList);
store('mycar', $scope.carList);
}, true);
$scope.remove = function(index){
$scope.carList.splice(index, 1);
}
$scope.plus = function(index){
$scope.carList[index].num ++;
$scope.carList[index].price += $scope.carList[index].initPrice;
}
$scope.minus = function(index){
$scope.carList[index].num --;
$scope.carList[index].price -= $scope.carList[index].initPrice;
}
}); app.controller("AnotherCtrl", function($scope) {
$scope.firstUser = 'Peter';
});