1

I have an <input type="file"> in ng-repeat and I want to call a function whenever the value of element changes for the <input type="file"> element in ng-repeat.

I tried calling a $(#"id").change() function but it is not working. I have tried using ng-change, but ng-repeat doesnt work when I use ng-change. This is my code:

IN HTML

<div ng-repeat="item in items">
    <input  type="file" accept="image/*" id="add_{{$index}}"/>
</div>

IN JS

$("#add_images").change(function() {
    alert("HI");
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Venkat
  • 39
  • 4

5 Answers5

2

Why you are mixing Angular and JQuery?

You have everything in Angular which you can use it easily!

In HTML

<div ng-repeat="item in items">
    <input  type="file" accept="image/*" id="add_images" ng-change="doSomething()"/>
</div>

In controller JS

$scope.doSomething = function(){
  //do whatever you want to
}
1

Angular doesn't support ng-change for input type=file github

but there are ways to trigger methods on the scope see my jsfiddle

<div>
  <div ng-controller='MyCtrl'>
    <pre>{{items | json }}</pre>
    <div ng-repeat="item in items">
      <input type="file" onchange='angular.element(this).scope().onchange(this)' />
    </div>
  </div>
</div>
angular.module('myApp', [])
  .controller('MyCtrl', function($scope) {
    $scope.items = ['test', 'test2'];
    $scope.onchange = function(that) {
      alert(that.value)
    }
  });
0

First thing you are repeating id inside ng-repeat. Id should be unique. I will suggest you to use.

<div ng-repeat="item in items">
  <input  type="file" accept="image/*" />
</div>

$index is the index of item.

Second use onchange function of Javascript

<div ng-repeat="item in items">
  <input  type="file" accept="image/*" onchange="angular.element(this).scope().myFunc()" id="add_images_$index"/>
</div>

Attach function to scope

$scope.myFunc = function() {
  alert("Hi");
}

Also refer ng-change on <input type="file" if you are trying to catch ng-change on input type file element.

Community
  • 1
  • 1
murli2308
  • 2,976
  • 4
  • 26
  • 47
0
<div>
  <div ng-app="myApp" ng-controller='MyCtrl'>    
    <div ng-repeat="item in items">
      <input type="file" ng-change="functionName()" />
    </div>
  </div>
</div>

var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
     $scope.functionName= function() {
     alert("hi your call worked successfully");
     }; 
});
0

you can use directive which is much better and cleaner.

HTML :

<div ng-repeat="item in items">
    <input  type="file" accept="image/*" id="add_{{$index}}" dir-change/>
</div>

JS:

directive('dirChange',function(){

  return {
    link : function(scope,ele){ 

      ele.bind('change',function(){ 
          //code

      });
    }
  }

})

Here is the Plunker

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53