AngularJS Directive To Listen For File Input Changes

Posted By Weston Ganger

Its handy to know when a file input has been changed so you can perform some action such as create a preview image.

Here we will make a directive to handle that

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

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

And you can use it in your HTML like so:

<pre>
<code class="language-markup">
<input type="file" custom-on-change="uploadFile($event)">



Related External Links:

- [Stack Overflow - AngularJS how to check for changes in file input fields](http://stackoverflow.com/questions/17922557/angularjs-how-to-check-for-changes-in-file-input-fields/17923521#17923521)

Article Topic:Software Development - Javascript

Date:July 09, 2015