Search code examples
javascriptjqueryangularjsopenfiledialoginput-type-file

input type file is unable to get the file name with file type in angularjs


I am creating a web app in which i have an input field

<input type="file" ng-model="getfilename" />

and a button

<button ng-click="clickfordetails()">Click Here!</button>

and a paragraph tag<P>{{file}}</p> when a user clicks on button after entering a file from input field he should get the file name in {{file}}

and here is my controller for the same

$scope.clickfordetails=function() {
    $scope.file=$scope.getfilename;
}

but i am unable to get the file name when i edit my controller to this

$scope.clickfordetails=function() {
    console.log($scope.getfilename);
}

the value in my console(google chrome) is Undefined

how i need to do this??


Solution

  • Use the below directive

    directive('customFileInput', [function () {
        return {
            link: function (scope, element, attrs) {
                element.on('change', function  (evt) {
                    var files = evt.target.files;
                    scope.filename=files[0].name
                });
            }
        }
    }]);