I'm trying to implement a simple shopping cart for books in two ways - (1)module and controller approach and (2) module and component approach. I used $scope.watch in the first one, so the code works. But I can't seem to implement it in the second part.
(1) - HTML:
<body ng-controller="CartControler" ng-init="updateTotal()">
<table>
<caption><b>My Books</b></caption>
<thead>
<tr>
<th>Title</th>
<th>Qty</th>
<th>$UnitPrice</th>
<th>Line Total</th>
<th>Total {{total | currency}}</th> //displays the correct amount
</tr>
.....
(1) - JS:
angular.module('myApp', [])
.controller('CartControler', function ($scope) {
$scope.books = [
{title: 'Absolute Java', qty: 1, price: 114.95},
{title: 'Pro HTML5', qty: 2, price: 27.95},
{title: 'Head First HTML5', qty: 1, price: 27.89}
];
$scope.total;
$scope.updateTotal = function(value) {
$scope.total = 0;
for(v in value){
$scope.total += value[v].price * value[v].qty;
}
return $scope.total;
}
$scope.$watch('books', function() {
$scope.updateTotal($scope.books);
}, true)
(2) - HTML:
<table>
<caption><b>My Books</b></caption>
<thead>
<tr>
<th>Title</th>
<th>Qty</th>
<th>$UnitPrice</th>
<th>Line Total</th>
<th>Total {{$ctrl.total | currency}} </th> //displays correct amount
but does not update on adding/removing/editing books
</tr>
</thead>
<tbody >
....
(2) - JS:
angular.module("cartApp")
.component('cartList', {
templateUrl: 'cart-list/cart-list.template.html',
init: 'updateTotal()',
controller: function CartListController() {
this.books = [
{title: 'Absolute Java', qty: 1, price: 114.95},
{title: 'Pro HTML5', qty: 2, price: 27.95},
{title: 'Head First HTML5', qty: 1, price: 27.89}
];
this.total;
this.updateTotal = function(value) {
this.total = 0;
for(v in value){
this.total += value[v].price * value[v].qty;
}
return this.total;
}
this.total = this.updateTotal(this.books);
In first implementation function updateTotal is invoked on initialization, because you have ng-init in HTML. In second implementation updateTotal is never invoked and this is the reason is not working. $watch is triggered only when the books list changed. In your case it doesn't. When additional book will be added in runtime, change detection will trigger watcher and call updateTotal function. To work second implementation from start, add this line of code:
this.total = this.updateTotal();