簡體   English   中英

在angularjs中使用指令獲取文件路徑

[英]using directive in angularjs for getting filepath

我正在用angularjs創建一個Web應用程序,但是我對angularjs中的指令不是很熟悉

我想由特定用戶獲取所選文件的文件路徑

<script>
 var myApp = angular.module('myApp', []);
myApp.controller('myCtrl',  function($scope, $http, $q){
    $scope.uploadFile=function(){
    var f = document.getElementById('file').files[0];
    console.log(f);
    console.log(files);
    }
});

myApp.directive('customFileInput', [function () {
        return {
            restrict: "EA",
            scope: false,
            link: function (scope, element, attrs) {
                element.on('change', function (evt) {
                    var files = evt.target.files;
                    scope.filename = files[0].name
                });
            }
        }
    }]);
</script>

這是我在其中使用angularjs應用程序,控制器和指令的腳本

但是我無法在按鈕單擊上調用指令

  <div ng-app="myApp" ng-controller="myCtrl">
  ggggg
<input id="file" type="file" ng-model="mdfile" ng-change="filepath()" class="form-control" custom-directive custom-file-input />
    <button ng-click="uploadFile()">upload me</button>
</div>

這是我上傳文件的按鈕和輸入字段

當我單擊按鈕時,出現以下錯誤

ReferenceError: files is not defined
    at b.$scope.uploadFile (image.html:22)
    at fn (eval at compile (angular.js:14539), <anonymous>:4:221)
    at b (angular.js:15628)
    at e (angular.js:25172)
    at b.$eval (angular.js:17378)
    at b.$apply (angular.js:17478)
    at HTMLButtonElement.<anonymous> (angular.js:25177)
    at Rf (angular.js:3487)
    at HTMLButtonElement.d (angular.js:3475)

如果我想獲取文件路徑並使用此指令,該怎么辦?

看到這個Plunkr:

https://embed.plnkr.co/dmNRL8bj7E5ZtnArQ0sm/

我更改了您的指令,使其在更改時提醒網址

  app.directive('customFileInput', [function () {
    return {
        restrict: "EA",
        scope: false,
        link: function ($scope, element, attrs) {
            element.on('change', function (evt) {
                var files = evt.target.files;
                var filename = files[0].name;
                alert(URL.createObjectURL(files[0]));
                });
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM