0

Super new to AngularJS so please be patient with me :)

We're using it to poll our API for updates while we process a repository (and after). On one particular page the data is loaded but not drawn to the screen. Highlighting the content, or resizing the browser causes a redraw and shows all angular values that weren't there a moment ago! Latest Chrome!

Just look: Everything starts at "0" or "-" but highlighting the page reveals "Optimized Images" and "Filesize Savings" content changes.

Live example:
MAY REQUIRE YOU HIT REFRESH TO HAVE THE ANGULAR DRAW FAIL

REQUIRES CHROME ~ Version 31.0.1650.63 m It works on Firefox!?! http://crusher.io/repo/alhertz/didthesaintswin/63f49d36e709dea172fe7e4bbacbcfd834f9a642

This appears to be very similar to this question, but there is no nested controller issue I can detect: Update page contents after GET request in AngularJS

When I try to add a $scope.$apply() I get this error: http://docs.angularjs.org/error/$rootScope:inprog?p0=$apply

This is the relevant code in the angular controller (coffeescript):

  do poll = ->
    $http.get("#{$location.absUrl()}/poll.json").success((data, status, headers, config) ->
      if $scope.continuePolling
        #console.log("still polling #{$location.absUrl()}")
        $scope.data = data
        $scope.TotalOptimizedImage = $scope.CalcTotalOptimizedImage(data.images)
        $scope.TotalImgSize = $scope.CalcTotalImgSize(data.images)
        $scope.SavedImgSize = $scope.CalcSavedImgSize(data.images)
        $scope.TotalSavings = ($scope.TotalImgSize - $scope.SavedImgSize + 0)
        $timeout(poll, 10000)
    )

Really not sure how to break this apart for fixing. Thoughts?

Community
  • 1
  • 1
Gant Laborde
  • 6,484
  • 1
  • 21
  • 30

1 Answers1

0

It looks like you need to call $scope.apply inside the callback to the http.get. The reason is that the callback will happen outside the controller digest. Sorry I'm not adept at coffee script but something like this:

 $http.get("#{$location.absUrl()}/poll.json").success((data, status, headers, config) 
  if $scope.continuePolling
    $scope.$apply(function() {  // wrap the stuff you want to update in the $scope.$apply
    #console.log("still polling #{$location.absUrl()}")
    $scope.data = data
    $scope.TotalOptimizedImage = $scope.CalcTotalOptimizedImage(data.images)
    $scope.TotalImgSize = $scope.CalcTotalImgSize(data.images)
    $scope.SavedImgSize = $scope.CalcSavedImgSize(data.images)
    $scope.TotalSavings = ($scope.TotalImgSize - $scope.SavedImgSize + 0)
  });
    $timeout(poll, 10000)
)

I would suggest that you use a safeApply function and there is a great timeFunctions service that might help you with the polling that I've used quite successfully in a couple projects. You can find it in this answer.

Community
  • 1
  • 1
lucuma
  • 18,247
  • 4
  • 66
  • 91