!DOCTYPE html>
<html ng-app>
<head>
<base/>
<title>Your Shopping Cart</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
<style>
</style>
</head>
<body ng-controller='CartController'>
<h1>购物清单</h1>
<div ng-repeat='item in items'>
<span>名称:{{item.title}}</span>
<input ng-model='item.quantity'/>
<span>单价:{{item.price | currency}}</span>
<span> 总价{{item.price * item.quantity | currency}}</span><!--currency过滤器显示美元符-->
<button ng-click="remove($index)" style="color: red"> 删除 </button>
</div>
<div><b>支付前价格: {{totalCart() | currency}} </b></div>
<div style="color: #445588">优惠: {{bill.discount | currency}} </div>
<div style="color: green"> <b>折后价格: {{subtotal() | currency}} </b></div>
</div>
<script>
function CartController($scope) {
$scope . bill = {};
$scope.items = [
{title : '苹果', quantity : 5, price : 3.95},
{title : '橘子', quantity : 8, price : 12.95},
{title : '菠萝', quantity : 8, price : 6.95}
];
//总价
$scope . totalCart = function () {
var total = 0 ;
for ( var i = 0 , len = $scope . items . length ; i < len ; i ++ ) {
total = total + $scope . items [ i ]. price * $scope . items [ i ]. quantity ;
}
return total ;
}
//折后价格
$scope . subtotal = function () {
return $scope . totalCart () - $scope.bill . discount ;
};
//打折条件
function calculateDiscount ( newValue , oldValue , scope ) {
$scope . bill . discount = newValue > 100 ? 90 : 0 ;
}
$scope . $watch ( $scope . totalCart , calculateDiscount );
//删除函数
$scope.remove = function(index) {
$scope.items.splice(index, 1);
};
}
</script>
</body>
</html>
运行结果:
