ng_developer
ng_developer

Reputation: 117

View is not updating in AngularJS

In my app, i am calculating total bill and displaying on my view. First time its work fine. But when I increment the $scope.bill_total it is not updating the view. But in console it is changing. I have tried $scope.$apply(). But it is throwing error.what are the reasons of view not get updating in general case Can anyone explain it?

HTML

 <div id="total" class="col col-30 cart-item text-right text-black">
            Bill Total<br/> ${{ bill_total }}
        </div>
<button class="button button-small button-light"  ng-click="increment()"> +</button>

JavaScript:

$scope.calculate = function () {
    $scope.bill_total = parseFloat($scope.gross_bill) + parseFloat($scope.taxes) + parseFloat($scope.tips);
}

$scope.calculate();

$scope.increment = function () {
    $scope.gross_bill++;
    $scope.calculate();
    console.log($scope.bill_total )
}       

Upvotes: 1

Views: 96

Answers (3)

hjl
hjl

Reputation: 2802

as we can only see part of your source code, it looks all good. to test if everyting is in the same digest scope, you can manually do an async apply:

$scope.increment = function () {
    setTimeout(function () {
        $scope.gross_bill++;
        $scope.calculate();
        $scope.$apply();
        console.log($scope.bill_total );
    });
} 

and pls also double check below points:

  • if bill_total is one-time binding {{ ::bill_total }}
  • if the directive scope is isolated with one-way binding bill_total

Upvotes: 1

Peter Ashwell
Peter Ashwell

Reputation: 4302

Need to see more of your code, but why are you updating gross_bill when you are expecting bill_total to change?

If you aren't using gross_bill in your template, it won't be watched and hence changing it's value won't redraw the view.

So, modify things that are bound in your template. If there's some reason I'm wrong and you need to do scope.apply, and maybe that's the case, try wrapping your code in a $timeout which will trigger a digest, is the 'recommended' solution preferred to calling apply directly.

notes on apply vs timeout

Upvotes: 1

Bill
Bill

Reputation: 25555

The problem is probably that $scope.bill_total is not an object and therefore cannot be watched. You need to change it to something like $scope.bill_total = {value: 3}. Then when you update the value it should be updated correctly in your view. There should be no reason to call $scope.apply since you are within a digest cycle already.

Make sure to change your html to :

<div id="total" class="col col-30 cart-item text-right text-black">
  Bill Total<br/> ${{ bill_total.value }}
</div>

Upvotes: -1

Related Questions