【问题标题】:Skip the upload button跳过上传按钮
【发布时间】:2017-09-17 18:30:23
【问题描述】:

我有一个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>

有谁知道如何修改代码并实现这一点?

【问题讨论】:

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


    【解决方案1】:

    我偶然发现只添加一行 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 2016-08-25
      • 2016-10-04
      相关资源
      最近更新 更多