最近看到的資源:
範例: http://tutorialzine.com/2013/08/learn-angularjs-5-examples/
影片教學: http://egghead.io/lessons
AngularJS 主要概念(參考 Oreilly AngularJS):
- Client-Side Templates
- MVC
- Data Binding
- Dependency Injection
- Directives
練習、修改了書中的 Shopping Cart 例子,ng_cart01.htm。
個人修改時的要點:
- ng-init 初始化。
- ng-repeat="item in items" 裡 $index 是預設的索引變數。
- ng-keyup 事件在 1.1.5 之後的版本才有效。
<html ng-app>
<head>
<title>菜籃</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</head>
<body ng-controller="basketController" ng-init="init()" style="margin: 30px">
<h4>新增項目</h4>
<div class="row">
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon">
項目名稱
</span>
<input type="text" class="form-control" ng-model="new_title" placeholder="項目名稱">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon">
單價
</span>
<input type="text" class="form-control" ng-model="new_price" placeholder="單價">
<span class="input-group-btn">
<button class="btn btn-default" ng-click="addItem()">新增</button>
</span>
</div>
</div>
</div>
<hr />
<div class="panel panel-default col-sm-4">
<div class="panel-body">
<h4>清單 總計: {{title_price | currency}}</h4>
</div>
<table class="table">
<tr>
<th>名稱</th>
<th>單價</th>
<th>數量</th>
<th>小計</th>
<th>移除</th>
</tr>
<tr ng-repeat="item in items">
<td>{{item.title}}</td>
<td>{{item.price | currency}}</td>
<td>
<input ng-model="item.quantity" class="form-control" ng-keyup="calc()">
</td>
<td>{{item.quantity * item.price | currency}}</td>
<td>
<button class="btn btn-default" ng-click="remove($index)">X</button>
</td>
</tr>
</table>
</div>
<script type="text/javascript">
function basketController($scope) {
$scope.items = [
{ title: "青菜", quantity: 2, price: 20},
{ title: "蘿蔔", quantity: 3, price: 30},
];
$scope.title_price = 0;
$scope.init = function() {
$scope.calc();
}
$scope.remove = function(index) {
$scope.items.splice(index, 1);
$scope.calc();
}
$scope.addItem = function() {
$scope.items.push({
title: $scope.new_title,
quantity: 1,
price: $scope.new_price
});
$scope.calc();
}
$scope.calc = function() {
var i, item;
$scope.title_price = 0;
for(i=0; i<$scope.items.length; i++) {
item = $scope.items[i];
$scope.title_price += item.price * item.quantity;
}
}
}
</script>
</body>
</html>
沒有留言:
張貼留言