2017-04-20 48 views
0

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

有谁知道如何修改代码和实现这一目标?

回答

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>