Search code examples
jqueryangularjsjquery-file-upload

Scope Issues in Getting Jquery-File-Upload to work with AngularJS


I'm trying to implement a multi-file upload feature and came across this http://blueimp.github.io/jQuery-File-Upload/angularjs.html.

In my form, I am using ng-switch to load in different parts of the form as part of a form wizard. The second part of the form requires the user to upload pictures and this is where things start to break for me. I understand why it's breaking -- ng-switch, with many other directives, creates a new scope. The work around is to use objects as opposed to "writing" directly to the scope -- $scope.booking.amount as opposed to $scope.amount

So how do I get jquery-file-upload, or any other 3rd party library for that matter, to "bind" correctly to my object and prevent these scope issues?

Relevant parts of jquery-file-upload:

Relevant parts of my code:

View

<div data-ng-switch="getCurrentStep()" data-ng-animate="'slide'">
<div data-ng-switch-when="one">
<!-- First part of form -->
    <textarea data-ng-model="viewing.remarks" type="text" rows="4" cols="10" placeholder="A short description of the property"></textarea>
</div>
<div data-ng-switch-when="two">
<!-- Second part of form -->
    <input type="file" name="files[]" multiple data-ng-disabled="disabled">
    <ul class="inline-list">
        <li data-ng-repeat="file in queue" data-ng-switch data-on="!!file.thumbnailUrl">
        <div class="preview" data-ng-switch-when="true">
            <a data-ng-href="{{file.url}}" title="{{file.name}}" download="{{file.name}}" data-gallery>
                  <img data-ng-src="{{file.thumbnailUrl}}" alt="">
                </a>         
                <a href="" class="text-center" data-ng-click="file.$cancel()" data-ng-hide="!file.$cancel">Cancel</a>
        </div>
        <div class="preview" data-ng-switch-default data-file-upload-preview="file"></div>
        </li>
    </ul>
</div>

Controller

The main thing is I have a viewing object which is called from a service.

$scope.viewing = new Viewing()

So in the current code context, how do I get $scope.queue, which is from jquery-file-upload, talking to my $scope.viewing object?


Solution

  • So the answer is actually quite straight forward.

    First I have to add the directive data-file-upload="options" inside the new scope created by the ng-switch. So this means moving it from <form data-file-upload ....> to a div inside the second ng-switch.

    After that, to bind it to my object it's simply

    $scope.queue = [];
    $scope.viewing.fileQueue = $scope.queue
    

    $scope.queue originates from the blueimp angular file and needed to be initialized in my controller first.