Muthukannan Kanniappan
Muthukannan Kanniappan

Reputation: 2079

input file change listener in a directive doesnt update scope variable [plunker attached]

I have a directive that contains file input. On change of file input I try to update some scope variables, it doesn't update it. When the commented out timeout is uncommented scope variables are updated.

I was under the impression that angular.element .on function does the safe apply (triggering a digest). I am not sure why it requires another $timeout here to work, Could someone shed some light on this behaviour?

Problem reproduced in below plunker. https://plnkr.co/edit/dHRInri9i21bR0gxe8q1?p=preview

app.directive('fileInput', function($timeout) {
  var directive;

  directive = {
    restrict: 'E',
    templateUrl: 'fileinput.html',
    link: function(scope, element) {
      element
        .find('input')
        .on('change', function(e) {
          console.log(e);
          scope.fileName = 'file name--->' + e.target.files[0].name;
          /*$timeout(function(){
            scope.fileSize = 'fileSize--->' + e.target.files[0].size;
          });*/
        });
    }
  };

  return directive;
});

directive template:

<input type="file" id="fileUpload" accept="image/*" />
<br>
{{fileName}}
<hr>
{{fileSize}}

Upvotes: 0

Views: 116

Answers (1)

Gaara
Gaara

Reputation: 78

element.on is either using jqLite or Jquery. So using scope.$apply is valid in this case as element.on is not AngularJs aware

plunker: https://plnkr.co/edit/hohU97QmjASwat139sEV?p=preview

Upvotes: 1

Related Questions