3

I'm using controller as syntax.

And when my file input changed, i want to trigger a function.

how to do that?

below is my code with $scope syntax

<input class="upload" type="file" accept="image/*" ng-model="image"
                onchange="angular.element(this).scope().uploadImage(this)">
Rob
  • 14,746
  • 28
  • 47
  • 65
Tran Thien Chien
  • 643
  • 2
  • 6
  • 17

3 Answers3

6

As found here, you could use a custom directive to listen for changes in your input file.

view.html:

<input type="file" custom-on-change="uploadFile">

controller.js:

app.controller('myCtrl', function($scope){
    $scope.uploadFile = function(event){
        var files = event.target.files;
    };
});  

directive.js:

app.directive('customOnChange', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var onChangeHandler = scope.$eval(attrs.customOnChange);
      element.bind('change', onChangeHandler);
    }
  };
});

View JSFIDDLE

Community
  • 1
  • 1
Matheno
  • 4,112
  • 6
  • 36
  • 53
3

you can use ng-change="nameOfFunction()" this will trigger when this input change

Or use HERE

abdoutelb
  • 1,015
  • 1
  • 15
  • 33
  • I dont think `ng-change` works in `` according to this: https://github.com/angular/angular.js/issues/1375 (I didnt test...). However `angular-file-upload` is indeed a possible solution. – pgrodrigues Jun 22 '16 at 11:58
2

Use angular scope.$watch. In your controller, add this:

scope.$watch("image", function(newValue, oldValue) {
   // Do anything you want here
   scope.uploadImage(newValue);
}

More information about scope.$watch: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Huy Hoang Pham
  • 4,107
  • 1
  • 16
  • 28