我在HTML中有一个上传图像输入:

<div class="row">
    <div class="col-md-12">
        <div class="form-group"
            ng-class="(uploadSgnCtrl.showUploadSgnErrorMessage && uploadSgnCtrl.dataIsNullOrEmpty(uploadSgnCtrl.param)) ? 'has-error' : ''">
            <label for="signatureImage" class="required">Signature Image</label>
            <div class="input-group">
                <input type="file" id="file" name="signatureImage"
                    class="form-control" data-file="uploadSgnCtrl.param"
                    ng-model="uploadSgnCtrl.param" file-upload>
            </div>
            <div class="row no-padding no-margin element-error-message">
                <ul class="no-padding no-margin">
                    <li ng-if="uploadSgnCtrl.dataIsNullOrEmpty(uploadSgnCtrl.param)"
                        class="no-padding no-margin">This field is Required</li>
                </ul>
            </div>
        </div>
    </div>
</div>

在我的指令a中有以下代码:
module.directive('fileUpload', function() {
    return {
        scope : {
            file : '=',
            accept : '=',
            showUploadSgnErrorMessage : '=' //this doesn't work
        },
        link : function(scope, el, attrs, ctrl) {
            console.log(ctrl)
            el.bind('change',
                    function(event) {
                        var files = event.target.files;
                        var file = files[0];

                        var validFormats = [ 'jpg', 'jpeg', 'png', 'JPG',
                                'JPEG', 'PNG' ];

                        var value = file.name
                        var ext = value.substr(value.lastIndexOf('.') + 1);

                        if (ext == '')
                            return;

                        if (validFormats.indexOf(ext) !== -1
                                && file.size < 2097152) {
                            scope.file = file;
                            scope.$apply();
                        } else {
                            scope.file = null;
                            console.log('file more than 2mb'); //working

                            ctrl.showUploadSgnErrorMessage = true; //not working
                            scope.showUploadSgnErrorMessage = true; //not working
                            console.log(ctrl.showUploadSgnErrorMessage); //not working
                            console.log(scope.showUploadSgnErrorMessage); //not working
                            scope.$apply();
                        }

                    });
        }
    };
});

我想要的是,如果我上传的文件超过2mb,它将触发“uploadSgnCtrl.showUploadSgnErrorMessage”为true,这是在我的ng类HTML代码中设置的。但上述代码不起作用(请参阅注释代码)。尽管console.log('file more 2mb')可以工作。我得到一个TypeError:r在它旁边没有定义。

最佳答案

如果您只需要访问控制器作用域并获取/设置一些值,就可以使用$root

scope.$root.showUploadSgnErrorMessage = true;

我假设您的uploadSgnCtrl引用是父控制器,它有一个$scope

10-06 05:01