角度指令变量未发送回rootscope

Angular directive variable not getting sent back to rootscope

本文关键字:rootscope 指令 变量      更新时间:2023-09-26

我有一个文件上传角度指令,当不放置在选项卡集中时,该指令有效。在下面的代码中,你会看到在选择并上传文件后,它会设置

 scope.$parent.file = file;

然而,在我的控制器中,当我尝试访问$scope.file时,它是未定义的。请参阅下面的指令、控制器和模板。同样,如前所述,如果我将模板放置在选项卡集(angular ui)的外部,则upload()函数有效-否则,我会收到"请选择要上传的文件"错误:

fileUpload.js:

'use strict';
var fileUploader = angular.module('fileUploader', []);
fileUploader.directive('file', function() {
    return {
        restrict: 'AE',
        scope: {
            file: '@'
        },
        link: function(scope, el, attrs){
            el.bind('change', function(event){
                var files = event.target.files;
                var file = files[0];
                scope.file = file;
                scope.$parent.file = file;
                scope.$apply();
            });
        }
    };
});

myController:

$scope.upload = function() {
            var bucket = new AWS.S3({ params: { Bucket: aws.public.bucket } });
            AWS.config.update({ accessKeyId: aws.public.access_key,
                                secretAccessKey: aws.public.secret_key });
            AWS.config.region = 'us-east-1';
            if($scope.file) {
                // Perform File Size Check First
                var fileSize = Math.round(parseInt($scope.file.size));
                if (fileSize > $scope.sizeLimit) {
                    toastr.error('Sorry, your attachment is too big. <br/> Maximum '  + $scope.fileSizeLabel() + ' file attachment allowed','File Too Large');
                    return false;
                }
                // Prepend Unique String To Prevent Overwrites
                var uniqueFileName = $scope.uniqueString() + '-' + $scope.file.name;
                var params = { Key: uniqueFileName, ContentType: $scope.file.type, Body: $scope.file, ServerSideEncryption: 'AES256' };
                bucket.putObject(params, function(err, data) {
                    if(err) {
                        toastr.error(err.message,err.code);
                        return false;
                    }
                    else {
                        // Upload Successfully Finished
                        toastr.success('File Uploaded Successfully', 'Done');
                        // Reset The Progress Bar
                        setTimeout(function() {
                            $scope.uploadProgress = 0;
                            $scope.$digest();
                        }, 4000);
                    }
                })
                    .on('httpUploadProgress',function(progress) {
                        $scope.uploadProgress = Math.round(progress.loaded / progress.total * 100);
                        $scope.$digest();
                    });
            }
            else {
                // No File Selected
                toastr.error('Please select a file to upload');
            }
        }

我的模板:

  <div id="videoEditForm" ng-show=" showAddVideoForm || showEditVideoForm">
            <tabset>
                <!-- Videos -->
                <tab id="webVideo">
                    <tab-heading>
                        <i class="fa  fa-film"></i>YouTube Video
                    </tab-heading>
                    <edit-video>video form</edit-video>
                </tab>
                <tab id="uploadVideo">
                    <tab-heading>
                        <i class="fa  fa-film"></i>Upload a Video {{file.name}}
                    </tab-heading>
                    <div class="panel-body">
                        <input class="bottom-marg-15" type="file" name="file" file></input>
                        <!-- Progress Bar -->
                        <div class="progress">
                            <div class="progress-bar" role="progressbar" aria-valuenow="{{ uploadProgress }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ uploadProgress }}%;">
                                {{ uploadProgress == 0 ? '' : uploadProgress + '%' }}
                            </div>
                        </div>
                        <a class="btn btn-primary btn-block btn-lg" ng-click="upload()">Upload</a>
                    </div>
                </tab>
            </tabset>
        </div>

当您的指令被添加到选项卡集时,scope$父对象不会指向控制器的作用域,而是指向选项卡或选项卡集作用域。

更好的方法是将file属性更改为指令中的双向绑定变量。然后,指令可以使用此变量来设置可以在控制器的作用域中使用的值。

指令定义:

fileUploader.directive('file', function() {
  return {
    restrict: 'AE',
    scope: {
        file: '='
    },
    link: function(scope, el, attrs){
        el.bind('change', function(event){
            var files = event.target.files;
            var file = files[0];
            scope.file = file;
            scope.$apply();
        });
    }
  };
});

用法:

<div file="aFile">

aFile将通过控制器范围中的一个变量

我发现了上面的问题。。。原来我错误地调用了$element.css。。。我用引号包装css,但应该是:

 link = function($scope, $element, $attrs){
                $scope.$watch('pos', function () {
                        console.log("position is: "+$scope.pos);
                       $element.css({
                          top: $scope.pos + 'px',
                          position: 'relative'
                        });
                        $attrs.style="top:'+$scope.pos+'px;position:relative;!important'";
                });
            };