Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass angularJS $index into onchange

Tags:

html

angularjs

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**)")
like image 690
ncohen Avatar asked Jun 30 '26 08:06

ncohen


1 Answers

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;

    // …
};
like image 145
Blackhole Avatar answered Jul 17 '26 16:07

Blackhole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!