<body ng-app='fruitApp'>
<!-- watch(wahtFN, wahtAction, deepWatch) -->
<!-- watchFn : 표현식을 나타내는 문자열, 변수가 될수도 있고 함수가 될 수도 있다 -->
<!-- watchAction(newValue, oldValue, scope) : watchFn이 변경되면 호출되는 함수나 표현식 -->
<!-- deepWatch : true, 감시 대상이 배열일 경우 모든 값의 변화를 관찰한다. -->
<!-- 리스너해지 : var dereg = $scope.$watch('someModel.somePropoerty', callbackOnChange()) ; -->
<!-- 리스너해지 : defeg(); 호출하면 해지됨 -->
<div ng-controller='fruitTableController'>
<div ng-repeat='fruit in fruits' ng-click='selectFruit($index)'
ng-class='{selected : $index==selectedRow}'>
<!-- 수량을 바꾸면, $watch의 등록된 함수가 호출된다 -->
<input ng-model='fruit.quantity'/>
<span>{{fruit.name}}</span>
<span>{{fruit.price}}</span>
<span>{{fruit.price * fruit.quantity}}</span>
</div>
salePercent :<input ng-model='salePercent'/><br>
<div> 전체 금액 : {{bill.totalCart || currency}} </div>
<div> 할인 금액 : {{bill.discount || currency}} </div>
<div> 결제 금액 : {{bill.subtotal || currency}} </div>
</div>
</body>
var app = angular.module('fruitApp',[]);
function __fruitTableController($scope){
$scope.bill ={};
$salePercent =0;
$scope.fruits=[
{name:'banana',price:'5000', quantity:1},
{name:'apple', price:'3000', quantity:1},
{name:'tomato',price:'4000', quantity:1},
];
// 클릭한 리시트의 밑줄
$scope.selectFruit = function(index){
$scope.selectedRow= index;
}
var calculateTotals = function(){
var total =0;
for(var i =0, len=$scope.fruits.length; i<len; i++){
total = total + $scope.fruits[i].price * $scope.fruits[i].quantity;
}
$scope.bill.totalCart = total;
$scope.bill.discount = total/100 * $scope.salePercent;
$scope.bill.subtotal = total - $scope.bill.discount;
}
// fruits 모델의 값을 감시하다가, 변화가 있으면 calc 함수를 호출한다.
// 배열일 경우 다 확인하기 위해서, true 인자를 준다.
$scope.$watch('fruits', calculateTotals, true);
$scope.$watch('salePercent', calculateTotals, true);
}
app.controller('fruitTableController',__fruitTableController);
.selected{
background-color: lightgreen;
}