barteloma
barteloma

Reputation: 6855

Angularjs file upload directive

I am creating a file upload directive to use in forms.

angular.module("app")
    .directive("myFileUpload", [function () {
        return {
            restrict: "E",
            template: '<input type="file" multiple class="form-control" placeholder="Select file">',
            scope: {
                files: "="
            },
            link: function (scope, element) {

                element.change(function (event) {
                    scope.files = event.target.files;
                    event.preventDefault();
                });

            }
        }
    }]);

I can use this directive in somewhere of my application.

<div class="col-sm-9">
    <input ng-model="myform.title">
    <my-file-upload files="myform.files"></my-file-upload>
</div>

And I want to list that selected files like this:

<div class="col-sm-9">
    <input ng-model="myform.title">
    <my-file-upload files="myform.files"></my-file-upload>
    <p ng-repeat="item in myform.files">{{item.filename}}</p>
</div>

If I do not enter text in input myform.title, the files does not list.

Upvotes: 1

Views: 1089

Answers (1)

Patrick Kelleter
Patrick Kelleter

Reputation: 2771

the callback of

element.change

happens outside of the "angular-world". you will need to let angular know that "something happened" try this instead

element.change(function (event) {
  scope.files = event.target.files;
  event.preventDefault();
  scope.$apply();
});

Upvotes: 1

Related Questions