Patrickkx Patrickkx - 1 month ago 10
AngularJS Question

AngularJS: Auto-update the total price

The html code:

<input placeholder='Total price' type="text" value="{{ totalPrice || '' }}" </input>


Angular code:

$scope.totalPrice = function() {
var total = 0;
if (itemsToBuy.length > 0) {
for (var i = 0; i < $scope.itemsToBuy.length; i++) {
total += $scope.itemsToBuy[i].price;
}
}
return total;
};


This recursion gives a right value, but I'm having problem with displaying it.

I want the totalPrice value to be displayed on the screen, in the input and auto-update it's value, when the
itemsToBuy
array changes it's length.

So once again, the
total
variable holds a correct value, but it is not displayed in the input.

Thanks for any further answers.

Answer

As K Scandrett pointed out, totalPrice is a function, so you need to execute it to display its return value. So {{totalPrice || ''}} should be {{totalPrice()}}.