0

I'm having a problem, i'm unable to get my ng-switch to work on my partials. What I'm trying to do is upload an image but before I upload it I must first check if the included image size doesn't reach 25kb.

Here is my controller code:

$scope.validateAvatar = function(files) {
    var fd = new FormData();
    $scope.filesize = files[0].size;
    $scope.filemaxsize = 25;
//Take the first selected file
fd.append("file", files[0]);

    $scope.uploadAvatar = function() {
        Api.uploadAvatar($scope.main.user.email, fd)
        .then(function(result) {
            console.log(result.data);
        }, function(result) {
            console.log(result);
        })
    };
};

and my partials code:

<form data-ng-submit="uploadAvatar()">
    <input type="file" name="file" onchange="angular.element(this).scope().validateAvatar(this.files)"/>

    <div ng-switch on="filesize / 1024 < filemaxsize">
        <div ng-switch-when="true">
            <input type="submit" value="Upload Avatar">
        </div>
        <div ng-switch-default>
            Please choose you avatar.
        </div>
    </div>

</form>

Also do you think my validation is enough when checking for the image file size, say what if the image included is size:20MB, will my validation still catch it? Sorry in the first place I haven't been able to make it work the switch statements first . :(

Danger14
  • 760
  • 2
  • 12
  • 33
Wondering Coder
  • 1,652
  • 9
  • 31
  • 51

1 Answers1

1

You need to call $scope.$apply() after you changed $scope.filesize manually.

BTW, why not just let $scope.filemaxsize = 25 * 1024;

Kabie
  • 10,489
  • 1
  • 38
  • 45
  • 1
    oh, okay its working now. This is my first time using $apply. The docs in angularjs is scary to read. @_@. Also by making $scope.filemaxsize = 25 * 1024 then my partials expression would just be filesize <= filemaxsize. Is this correct? – Wondering Coder Aug 24 '13 at 09:32
  • @WonderingCoder: Yes. – Kabie Aug 24 '13 at 09:34
  • this is weird, it's working when I refresh the page just for testing. but originally my app flows like this, when login -> profile and from profile page that where I upload the avatar. I had to click the choose a file button twice for the upload button to appear. Why is it like that? – Wondering Coder Aug 24 '13 at 09:55
  • 1
    @WonderingCoder: is `$scope.filemaxsize` only defined here? I think this should be in top level. Perhaps you insert `$scope.$apply()` between `$scope.filesize` and `$scope.filesize`? – Kabie Aug 24 '13 at 10:02
  • oh yeah! its working now. woah, thanks a many men! BTW, this is out of the topic. Since I'm building a SPA web, refreshes in between pages are not allowed, right? But how do you handle if the user refreshes page? You get what I mean right? – Wondering Coder Aug 24 '13 at 10:14