2017-04-20 58 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>