跳过上传按钮

时间:2017-04-20 22:44:13

标签: javascript angularjs forms file-upload angularjs-directive

我有一个mean-stack申请。我想实现一个按钮,用户可以通过该按钮上传缩略图。我跟着this link,它有效。

但是,我想跳过upload按钮:用户点击Choose file按钮,选择一个本地文件,然后我希望自动上传文件 必须单击upload按钮。 existing code使用指令来控制input,我不知道如何修改它:

<!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>

有谁知道如何修改代码并实现此目的?

1 个答案:

答案 0 :(得分:0)

偶然地,我意识到只添加一行scope.uploadFile()可以解决问题:

  <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>