0

I am trying to create a upload component but my view isn't updating when onchange event fires. I see the file.names being logged but nothing is happening.

I am using a directive because I would like to be able to just drop my package into a project and then enable the file uploader with <upload url='/fileserver'></upload>.

Controllers:

var controllers = {

  UploadCtrl: function ($scope) {

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

    $scope.upload = function (element) {
      $scope.$apply(function ($scope) {
        $scope.files = element.files;
      });
    };

    $scope.$watch('files', function () {

      for (var i = 0; i < $scope.files.length; i += 1) {

        var current = $scope.files[i];
        var reader = new FileReader();

        reader.onload = (function (file) {
          return function (env) {
            console.log(file.name);
            $scope.images.push({ name: file.name, src: env.target.result });
          }
        }(current));

        reader.readAsDataURL(current);
      }

    }, true);

  }

};

Directives:

var directives = {

  upload: function ($compile) {

    return {
      restrict: 'E',
      link: function (scope, element, attr) {
        scope.url = element.attr('url');
        element.html($compile(template)(scope));
      }
    };

  }

};

Template var (it's a cs file cause of multi line strings)

template = """
<div ng-controller='UploadCtrl'>
  <input type='file' multiple onchange='angular.element(this).scope().upload(this)' />

  <div ng-repeat='image in images'>
    {{image.name}}: <img ng-src='{{image.src}}' width='80' height='80' />
  </div>
</div>
"""

1 Answer 1

5

You may need to use $apply to update the images:

$scope.$apply(function () {
    $scope.images.push({ name: file.name, src: env.target.result });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.