LoginSignup
6
7

More than 5 years have passed since last update.

AngularJSで<input type="file">のonchangeイベントをハンドリングする

Last updated at Posted at 2015-08-28

<input type="file">にファイルが設定されたタイミングでスコープ内で定義した関数を実行したい時、普通にng-changeを要素につけても動かない。

<input type="file" ng-change="parseFile()">

これでは動かない。

ちょっと無理やりだけど、こうすれば動く。

<input type="file" onchange="angular.element(this).scope().parseFile(this)">
angular.module('App', [])
  .controller('MyCtrl', function($scope) {
    $scope.parseFile = function(fileElement) {
      var file = fileElement.files[0];
      console.log(file);

      $scope.fileType = file.type;
      $scope.fileName = file.name;

      $scope.$apply();
    };
  });

あとはfile.typefile.nameを調べるなりFileReaderを使って中身を読むなりご自由に。
なお、このコールバック関数内でモデルオブジェクトを変更した場合は、$scope.$apply()を呼ばないと変更が反映されません。

参考: http://stackoverflow.com/questions/17922557/angularjs-how-to-check-for-changes-in-file-input-fields

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7