File Upload with Angular Material

后端 未结 12 1229
抹茶落季
抹茶落季 2021-01-30 15:48

I\'m writing an web app with AngularJS and angular-material. The problem is that there\'s no built-in component for file input in angular-material. (I feel that file uploading d

12条回答
  •  青春惊慌失措
    2021-01-30 16:50

    Based on this answer. It took some time for me to make this approach working, so I hope my answer will save someone's time.

    DEMO on CodePen

    Directive:

    angular.module('app').directive('apsUploadFile', apsUploadFile);
    
    function apsUploadFile() {
        var directive = {
            restrict: 'E',
            templateUrl: 'upload.file.template.html',
            link: apsUploadFileLink
        };
        return directive;
    }
    
    function apsUploadFileLink(scope, element, attrs) {
        var input = $(element[0].querySelector('#fileInput'));
        var button = $(element[0].querySelector('#uploadButton'));
        var textInput = $(element[0].querySelector('#textInput'));
    
        if (input.length && button.length && textInput.length) {
            button.click(function (e) {
                input.click();
            });
            textInput.click(function (e) {
                input.click();
            });
        }
    
        input.on('change', function (e) {
            var files = e.target.files;
            if (files[0]) {
                scope.fileName = files[0].name;
            } else {
                scope.fileName = null;
            }
            scope.$apply();
        });
    }
    

    upload.file.template.html

    
    
        Choose file
    
    
        
    
    

提交回复
热议问题