Angular指令变量未被发送回rootscope

时间:2014-09-03 18:14:44

标签: javascript angularjs angularjs-scope angular-ui

我有一个文件上传角度指令,当放置在tabset内时无效。 在下面的代码中,您将看到在选择并上载文件后,它会设置

 scope.$parent.file = file;

但是在我的控制器中,当我尝试访问$ scope.file时,它是未定义的。请参阅下面的指令,控制器和模板。同样,如上所述,如果我将模板放置在tabset的外部(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>

2 个答案:

答案 0 :(得分:0)

当您的指令添加到tabset时,范围。$ parent将不会指向您的控制器范围,而是指向选项卡或tabset范围。

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

指令定义:

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将由控制器范围内的变量

组成

答案 1 :(得分:0)

我发现上述问题...... 结果我错误地调用了$ 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'";

                });
            };