Angular 自定义指令在输入字段更改时调用函数

Angular custom directive calls function on change of input field

我有一个在 DOM 上放置文件上传输入字段的指令,然后我希望能够在该文件更改时调用函数。如何在不将更改功能放在编译器区域的情况下使其工作?我知道它不属于那里,因为有人告诉我编译器占用的内存更多,应该只用于预渲染。

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

试试这个:

<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);
    };
});

这是工作fiddle