3

I have an input file within a ng-repeat in my angularJS app. I need to pass the $index variable to the onchange attribute. I'm using onchange and not ng-change because I need the uploaded object (see this post)

In the following code I get 'Uncaught ReferenceError: $index is not defined'

Jade code sample:

div.input-group(ng-repeat='filename in filenames track by $index') 
    input(type='file', onchange="angular.element(this).scope().file_changed(this.files, **$index**)")
Community
  • 1
  • 1
Nate
  • 7,606
  • 23
  • 72
  • 124

1 Answers1

8

In the onchange attribute, the scope is only accessible via angular.element(this).scope(). That's the method you use to call the file_changed() function, and you should use the same in order to have access to the $index attribute:

 <input type="file" onchange="angular.element(this).scope().file_changed(this.files, angular.element(this).scope().$index)" />

Notice that this is becoming pretty long! A solution is to simply pass the DOM element to the function, and obtain all the informations from it:

 <input type="file" onchange="angular.element(this).scope().file_changed(this)" />
$scope.file_changed = function (element) {
    var index = angular.element(element).scope().$index;
    var files = element.files;

    // …
};
Blackhole
  • 20,129
  • 7
  • 70
  • 68
  • @ncohen I'm pretty sure `var index = $scope.$index;` should perfectly work too. Can you try it? – Blackhole Jun 01 '14 at 19:51
  • @ncohen Inside the `file_changed()` method, I mean. No? – Blackhole Jun 01 '14 at 20:10
  • var index = angular.element(ele).scope().$index; always return 0. any idea pls? – beewest Oct 27 '17 at 13:14
  • @beewest A [MCVE](https://stackoverflow.com/help/mcve) will be necessary to help you. I can only advice you to open a question for your case. Don't hesitate to link to this one to show your research effort. – Blackhole Oct 30 '17 at 18:53
  • I have used the same .in my case I wants to uplaod different file with different rows . Using above solution index always return zero for every row .could you please assist .thank you – Suri Oct 13 '18 at 04:29