Search code examples
angularjsscoperootscope

Angular JS $scope.$on in a directive don't affect scope variable


I made a XHR upload Angular service where I'm trying to broadcast the upload progress via $rootscope

...  
xhr.upload.onprogress=function (evt){
      if (evt.lengthComputable) {
        percentComplete = Math.round((evt.loaded / evt.total)*100); 
        console.log(percentComplete)
        $rootScope.$broadcast('upload:progress', percentComplete);
      }else{
        $rootScope.$broadcast('upload:progress', 'not computable');
      }
    }
...

and the directive is

...
$scope.$on('upload:progress', function (event,data) {
  console.log('progress ' + data)
  $scope.progress = data
})
...

the html file is:

<div ng-controller="uploadController">    
    <input class="selectFile" type="file" multiple ng-model="files" file-change></input>
    <br><br>
    Selected: {{ files.length }}
    {{files}}
    <br><br>
    <a href="" ng-click="upload()">Start Upload</a>
    -- {{progress}}
</div>

the console write both the logs correctly (the one from the xhr.upload.onprogress and the other in the $scope.$on ) but the $scope.progress not change....

what's wrong?

Thank You!


Solution

  • Since it's an async call, which is outside AngularJS lifecycle, you need to run $scope.$apply explicitly to trigger a $digest, which will update the view:

    $scope.$apply(function () {
        $scope.progress = data;
    });