ng-model for `<input type=“file”/>` (with directive DEMO)

后端 未结 12 2275
北恋
北恋 2020-11-21 06:40

I tried to use ng-model on input tag with type file:


But after selecting a file, in

12条回答
  •  心在旅途
    2020-11-21 06:43

    I had to modify Endy's directive so that I can get Last Modified, lastModifiedDate, name, size, type, and data as well as be able to get an array of files. For those of you that needed these extra features, here you go.

    UPDATE: I found a bug where if you select the file(s) and then go to select again but cancel instead, the files are never deselected like it appears. So I updated my code to fix that.

     .directive("fileread", function () {
            return {
                scope: {
                    fileread: "="
                },
                link: function (scope, element, attributes) {
                    element.bind("change", function (changeEvent) {
                        var readers = [] ,
                            files = changeEvent.target.files ,
                            datas = [] ;
                        if(!files.length){
                            scope.$apply(function () {
                                scope.fileread = [];
                            });
                            return;
                        }
                        for ( var i = 0 ; i < files.length ; i++ ) {
                            readers[ i ] = new FileReader();
                            readers[ i ].index = i;
                            readers[ i ].onload = function (loadEvent) {
                                var index = loadEvent.target.index;
                                datas.push({
                                    lastModified: files[index].lastModified,
                                    lastModifiedDate: files[index].lastModifiedDate,
                                    name: files[index].name,
                                    size: files[index].size,
                                    type: files[index].type,
                                    data: loadEvent.target.result
                                });
                                if ( datas.length === files.length ){
                                    scope.$apply(function () {
                                        scope.fileread = datas;
                                    });
                                }
                            };
                            readers[ i ].readAsDataURL( files[i] );
                        }
                    });
    
                }
            }
        });
    

提交回复
热议问题