I am not using some complex directive, but rather simple multiplication and angular's 2-way binding seems to fail. When I say fail, it's not updating the view when I multiply. But when I click on some UI element or change the view in some way like click a radio button. The value magically appears. After some investigation, I found out that the apply is not being called when I multiply. So I added a $scope.$apply(function(){}). Which seem to fix it. But as I read in some post. You should never try explicitly calling $apply. Which begs the question. What the hell is happening? The console.log() is showing the changed value but the value is not being applied in the view. Also I am not directly manipulating the scope. For ex.
$scope.calculateOutstationCharges = function() {
if ($scope.customer.calculatedDistance !== 0) {
console.log($scope.customer.kmlimit * $scope.carPricing.perKmCharge * $scope.customer.days);
if (($scope.customer.calculatedDistance * 2) < $scope.carPricing.kmlimit * $scope.customer.days) {
$scope.customer.totalprice_outstation = $scope.carPricing.kmlimit * $scope.carPricing.perKmCharge * $scope.customer.days + $scope.customer.driverCharge;
//console.log($scope.customer.totalprice_outstation). This value is not updated in the view
} else {
$scope.customer.totalprice_outstation = ($scope.customer.calculatedDistance * 2 * $scope.carPricing.perKmCharge)+ $scope.customer.driverCharge;
//console.log($scope.customer.totalprice_outstation); nor is this one
}
$scope.customer.totalprice_outstation += $scope.customer.extra_outstation;
}
$scope.customer.driverCharge = $scope.carPricing.driverCost;
$scope.$digest(); //this does it but with $apply in progess error.
};
Values are updated in the next digest cycle, not in the cycle in which values are being created. If anyone of you has encountered similar what did you do to solve it? Thanks
$scope.CalculateOutstationCharges is called from outside of context of angular (am i right on this?).
Angular doesn't know that the $scope variables are changed. You need to explicity tell the angular this. To achieve that, you have to call,
$timeout(function(){$scope.$apply();})
Which would wait for the current digest cycle to complete. Then it will apply changed $scope variables on DOM.