Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update UI when scope object changes value internally to the scope of the controller

I am writing a simple little file uploader where I am taking the input files into $scope.files and uploading through an ajax call and then on success I am moving $scope.files to $scope.successfulUploads object. I want to display the list of successfulUploads inline as soon as there is a value set to it, it works with the $scope.files object and the console shows $scope.successfulUploads as it should be. I just need to write an observable, if you will.

Here is my code:

Controller

$scope.files = [];
$scope.successfulUploads = [];

$rootScope.$on('upload:success', function() {
    //console.log('Controller: on `success`');
    for (var i = 0; i < $scope.files.length; i++) {
        $scope.successfulUploads.push($scope.files[i]);
    }
    $scope.files = [];
    console.log('successfulUploads: ' + $scope.successfulUploads);
});

HTML:

<span class="span2 btn btn-success fileinput-button">
    <span>Add Files</span>
    <input type="file" multiple ng-model="files" file-change>
</span>
<table class="table table-hover table-striped">
    <tbody>
        <tr ng-repeat="file in successfulUploads">
            <td>{{file.name}}</td>
            <!--<td><a href="#" class="btn btn-danger">Delete</a></td>-->
        </tr>
    </tbody>
</table>
<div class="muted text-left">Uploaded: {{ successfulUploads.length }}</div>
</div>

As I said, when I use ng-repeat="file in files" it works beautifully.

And before anyone suggests using blueimps file uploader, yes it is a great looking file uploader with great functionality, but I need this to work with my angular module I've already defined, which when I was trying to convert it over it stopped working. Today I downloaded the full source and ran it "as-is" on my localhost it was giving me the same exact error and I am on a deadline. Maybe at a later date I can revisit it.

like image 933
Jonathan Jones Avatar asked Jun 19 '13 04:06

Jonathan Jones


1 Answers

Right after the second:

$scope.files = [];

Add:

$scope.$apply()

Then it should work.

like image 123
Nir Avatar answered Nov 24 '22 07:11

Nir