Reputation: 1251
I am working in a project with ng-cart directive. This directive has a service which includes a function totalCost()
that updates the total amount added to a shopping cart.
In order to show it in the view, I wrote this in my controller:
this.totalCost = ngCart.totalCost();
The value shown in the view is correct, but the problem is that this value doesn't update when I add/remove items from the cart, but only when I refresh the page.
I tried with
$scope.$watch('ngCart.totalCost()', function() {
this.totalCost = ngCart.totalCost();
});
But then totalCost
doesn't show in the view at all.
You can check a plunkr of my code here
Thanks in advance
Upvotes: 0
Views: 162
Reputation: 856
Change to,
$scope.$watch('ngCart.totalCost()', function() {
this.totalCost = ngCart.totalCost();
}.bind(this));
Because the watch callback is called by angular so, the this value in this function doesn't point to the controller's instance.
Here is your plunk, http://plnkr.co/edit/HoEC0obWOPFLWbSojO7F?p=preview
I have changed the watch definition in it because ngCart.totalCost is not a property on the scope.
Upvotes: 1