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

后端 未结 12 2278
北恋
北恋 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:58

    This is a slightly modified version that lets you specify the name of the attribute in the scope, just as you would do with ng-model, usage:

        
    

    Directive:

    .directive('myUpload', function() {
        return {
            link: function postLink(scope, element, attrs) {
                element.find("input").bind("change", function(changeEvent) {                        
                    var reader = new FileReader();
                    reader.onload = function(loadEvent) {
                        scope.$apply(function() {
                            scope[attrs.key] = loadEvent.target.result;                                
                        });
                    }
                    if (typeof(changeEvent.target.files[0]) === 'object') {
                        reader.readAsDataURL(changeEvent.target.files[0]);
                    };
                });
    
            },
            controller: 'FileUploadCtrl',
            template:
                    '' +
                    '' +
                    'Replace Image' +
                    '' +
                    '',
            restrict: 'E'
    
        };
    });
    

提交回复
热议问题