Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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: () => {
        },
      };
    },
  };
}]);
share|improve this question
up vote 0 down vote accepted

Try this instead:

<p>
  Select a file, and you should see an alert message
</p>

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

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 = event.target.files[0].name;
        alert('file was selected: ' + filename);
    };
});

here is the working fiddle

share|improve this answer
    
I thought you could only use ng-change with ng-model? ng-model does not work with a file :/ docs.angularjs.org/api/ng/directive/ngChange – Tori Huang Jul 1 at 15:26
    
@ToriHuang I edited my original post. This should work for what you need – Justin Herter Jul 1 at 15:29
    
That's awesome detail, thanks! – Tori Huang Jul 1 at 16:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.