Tori Huang Tori Huang - 1 year ago 34
AngularJS Question

Angular custom directive calls function on change of input field

I have a directive that places a file upload input field on the DOM, and I then want the ability to call a function when that file is changed. How can I get an on change function to work without placing it in the compiler area? I know it doesn't belong there, as I've been told the compiler is more memory intensive and should only be used for pre-render stuff.

angular.module('myApp').directive('customDirective', ['$http', function ($http) {

return {
controller() {

compile(element) {
const $fileinput = $('<input type="file" accept=".csv">').appendTo(element);
return {
controller: () => {
$fileinput.on('change', (e) => {
// Stuff happens
link: () => {

Answer Source

Try this instead:

  Select a file, and you should see an alert message

<div ng-app="myApp" ng-controller="myCtrl">
    <input type="file" custom-on-change="uploadFile"/>

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

myApp.controller('myCtrl', function($scope) {
    $scope.uploadFile = function(){
        var filename =[0].name;
        alert('file was selected: ' + filename);

here is the working fiddle