0

With reference to question File pick with Angular JS, on file reader's on load i want to modify a parent scope's property. Consider

$scope.fileLoaded = false; //initially
$scope.file_changed = function(element, $scope) {

 $scope.$apply(function(scope) {
     var photofile = element.files[0];
     var reader = new FileReader();
     reader.onload = function(e) {
        $scope.fileLoaded = true;  // I intend to do!
        ...
     };
     reader.readAsDataURL(photofile);
 });

});

How do i achieve this for HTML:

<input ng-model="photo"
   onchange="angular.element(this).scope().file_changed(this)"
   type="file" accept="image/*" />

It fails every time with error Cannot set property 'fileLoaded' of undefined.

Community
  • 1
  • 1
rahul
  • 100
  • 8

1 Answers1

1

Couple of things.

  1. use ng-change instead of onchange.
  2. do this in a directive. You don't want to be accessing elements in your controller. You can two-way bind the fileLoaded in your directive so you can access it in your controller if you'd really like to, or you can encapsulate all your functionality into a nice directive.

I wrote a sort-of-similar directive awhile back, you can check it out here: https://github.com/jrowny/SpriteHero/blob/master/js/directives/file.js I wrote that before I really knew angular that well so it could be a little messy. Also, it doesn't use the filefield directly, just invoked from a random link.

Angular is really a mess if you don't master directives pretty early on. Otherwise it's like you've got a ladder with only a few rungs provided.

Jonathan Rowny
  • 7,588
  • 1
  • 18
  • 26
  • Cannot use ng-change for input type file. https://github.com/angular/angular.js/issues/1375 – rahul Aug 09 '13 at 10:25