0

What i'm trying to do is update the percentage value (of data downloaded) which i received from service. I am calling $emit to update the controller and in turn value on $scope

$rootScope.$emit('event:activityWithResults', results);

and in my controller I am doing this

$rootScope.$on('event:activityWithResults', function (event, results){
  $scope.percentage = $scope.percentage || {};
  $scope.percentage.value = results.percentageComplete + "%";
  $log.debug("$scope.percentage:" + JSON.stringify($scope.percentage));
});

I do see in the logs that value on $scope is being updated on interval (I am not calling $emit for every change but regular interval of say 4 or more percentage of data downloaded. In my html I am simply showing this value {{percentage.value}} But this value doesn't update on UI but it updates only once or twice.

What is wrong here?

Gaurav18ca
  • 63
  • 1
  • 5
  • from where you are `$emit` the event? Is it from any `jQuery` listener? If yes then you need to run digest cycle to udpate the Angular DOM by using `$apply()` – Pankaj Parkar Sep 02 '15 at 18:03
  • No its from angular service (same module) but the service is basically a file downloader – Gaurav18ca Sep 02 '15 at 18:06
  • Could you please add the code from where you are `emitting` the event – Pankaj Parkar Sep 02 '15 at 18:07
  • `code` eventDispatcher.activityWithResults = function (progressResult){ if (progressResult.lengthComputable){ var percentageComplete = Math.round(100 * progressResult.loaded / progressResult.total); if (Math.abs(percentageComplete - downloadPercentage) >= 4 ){ downloadPercentage = percentageComplete; var results = { percentageComplete: angular.copy(percentageComplete) }; $rootScope.$emit('event:activityWithResults', results); } } }; `code` – Gaurav18ca Sep 02 '15 at 18:09
  • 1
    Is the file downloader an asyn activity outside angular context? if so you will have to manually trigger the digest cycle with `$rootScope.$apply` or `digest` and since manual invocation is recommended to be at the top of the call stack you should do it in the service after emit operation. – PSL Sep 02 '15 at 18:10
  • Please update the code in the question and what is `eventDispatcher`, i believe this could well be one of many duplicates that needs scope.apply. :) – PSL Sep 02 '15 at 18:11
  • @PSL thats what I asked..we need a code who is actual initiator of the event..must be some event which is out of angular context,, – Pankaj Parkar Sep 02 '15 at 18:13
  • Awesome yes $digest() is what i missed! Thank you PSL it worked. I actually tried the approach updating value on non scope variable inside Controller $rootScop.$on and then use that variable in $scope.$watch and called $apply but it didnt work. Calling digest makes sense – Gaurav18ca Sep 02 '15 at 18:16

0 Answers0