2

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: () => {
        },
      };
    },
  };
}]);

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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
@ToriHuang I edited my original post. This should work for what you need
I'm getting: TypeError: event is undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.