Shamoon
Shamoon

Reputation: 43649

How do I upload a file with AngularJS?

Here is my HTML:

<button class="btn btn-default" ng-click="selectFile()">Choose file</button>
<input type="file" accept="image/*" name="file" style="display: none;" id="photo-file" fileupload="uploadme">

In my controller, I have:

$scope.selectFile = function() {
  $("#photo-file").click();
}

I also created a directive:

angular.module("MyApp")
  .directive("fileupload", function($rootScope) {
    return {
      scope: {
        'fileupload': "="
      },
      link: function(scope, element, attributes) {
        return element.bind("change", function(changeEvent) {
          return scope.$apply(function() {
            return scope.fileread = changeEvent.target.files[0];
          });
        });
      }
    };
  }
);

But something is missing. When I select the file to upload, I want it to run a function in the controller. How can I do this?

Upvotes: 1

Views: 612

Answers (1)

artur grzesiak
artur grzesiak

Reputation: 20348

If you are okay with it, I can recommend using an external module. Here is something I tried and was pretty happy with it.

Upvotes: 1

Related Questions