摘要:實作 ng-click 事件,並將資料新增到 carts 模型物件中
================================HTML
<!DOCTYPE html>
<html ng-app>
<head>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="MainCtrl">
Product Name:<input type="text" ng-model="PName"><br>
Product Price:<input type="number" ng-model="Price"><br>
Product quantity:<input type="number" ng-model="Qty"><br>
<br>
Purchase Product: {{PName||'N/A'}}
<br>
Total price: {{Price* Qty||0 | currency:'NT$ '}}
<br>
Total price: NT$ {{subtotal()||0 | number:0}}
<br> <br>
<button ng-click="add()">Add to Shopping Car</button>
<br>
<!--<pre>{{carts|json}}</pre> -->
<br>
<table class="table">
<tr>
<th>#</th>
<th>商品名稱</th>
<th>商品價格</th>
<th>購買數量</th>
<th>小計</th>
</tr>
<tr ng-repeat="car in carts">
<td></td>
<td>{{car.PName}}</td>
<td>{{car.Price}}</td>
<td>{{car.Qty}}</td>
<td>{{car.Price * car.Qty}}</td>
</tr>
</table>
</body>
</html>
====================================JS
function MainCtrl($scope)
{
$scope.Price = 1;
$scope.Qty = 5;
$scope.PName = "T-shirt";
$scope.subtotal = function(){
var result = $scope.Price * $scope.Qty;
if($scope.Qty > 9) result *= 0.9;
return result;
};
$scope.carts = [];
$scope.carts.push({
PName: 'T-Shirt',
Price: 199,
Qty: 3
});
$scope.carts.push({
PName: 'Shoes',
Price: 1800,
Qty: 2
});
$scope.carts.push({
PName: 'Eye glasses',
Price: 1000,
Qty: 5
});
$scope.add = function()
{
$scope.carts.push({
PName: $scope.PName,
Price: $scope.Price,
Qty: $scope.Qty
});
};
}