0

I have a mean-stack application. I want to implement a button by which users could upload a thumbnail image. I have followed this link, which works.

However, I want to skip the upload button: users click on the Choose file button, choose a local file, then I want the file to be uploaded automatically without having to click on the upload button. The existing code uses a directive to control the input, I don't know how to modify that:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body ng-app="app" ng-controller="Ctrl">
  <input type="file" file-model="myFile" />
  <button ng-click="uploadFile()">Upload</button>
  <script>
    var app = angular.module('app', []);
    app.controller('Ctrl', ['$scope', function($scope) {
      $scope.uploadFile = function() {
        // $scope.myFile is available here
        alert("uploadFile");
      }
    }]);

    angular.module('app').directive('fileModel', ['$parse', function($parse) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function() {
            scope.$apply(function() {
              modelSetter(scope, element[0].files[0]);
            });
          });
        }
      };
    }]);
  </script>
</body>
</html>

Does anyone know how to modify the code and achieve this?

Community
  • 1
  • 1
SoftTimur
  • 5,630
  • 38
  • 140
  • 292

1 Answers1

0

By accident, I realise adding just one line scope.uploadFile() does the trick:

  <script>
    var app = angular.module('app', []);
    app.controller('Ctrl', ['$scope', function($scope) {
      $scope.uploadFile = function() {
        // $scope.myFile is available here
        alert("uploadFile");
      }
    }]);

    angular.module('app').directive('fileModel', ['$parse', function($parse) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function() {
            scope.$apply(function() {
              modelSetter(scope, element[0].files[0]);
            });
            scope.uploadFile() // works
          });
        }
      };
    }]);
  </script>
SoftTimur
  • 5,630
  • 38
  • 140
  • 292