简体   繁体   English

角不更新控制器中的$ scope变量

[英]angular not updating $scope variable in controller

I have a directive to upload a file to the browser 我有指令将文件上传到浏览器

angular.module('angularPrototypeApp')
.directive('upload', ['$parse', function ($parse) {
return {
    restrict: 'A',
    scope: false,
    link: function(scope, ele, attrs) {

        var fn = $parse(attrs.upload);
        ele.on('change', function(onChangeEvent){
            var reader = new FileReader();

            reader.onload = function(onLoadEvent) {
                scope.$apply(function(){
                    fn(scope, {$fileContents: onLoadEvent.target.result} );
                });
            }

            reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
        })

    }
  };
}]);

The code is taken from here: https://veamospues.wordpress.com/2014/01/27/reading-files-with-angularjs/ 代码是从这里获取的: https : //veamospues.wordpress.com/2014/01/27/reading-files-with-angularjs/

The view looks like this: 该视图如下所示:

<progressbar class="progress-striped active" value="dynamic" </progressbar>
<input type="file" upload="parseInputFile($fileContents)">

In the controller I do the following: 在控制器中,执行以下操作:

angular.module('angularPrototypeApp')
.controller('Gc2xlsxCtrl', ['$scope', 'blockUI', function ($scope,  $timeout, blockUI) {

$scope.dynamic = 0;

$scope.parseInputFile = function($fileContents){
    $scope.$broadcast('fileUploaded', $fileContents);
}

$scope.$on('fileUploaded', function(event, fileContents) {
    if(fileContents !== undefined){
        blockUI.start();

        //a lot of work is done herem takes between 2 and 20 Seconds
        for(var i = 1; i <= 100; i++){
            $scope.dynamic += 1;
        }

        blockUI.stop();
    }
});
}]);

My problem is that the update to $scope.dynamic is shown in the view only after the whole method has finished. 我的问题是,仅在整个方法完成后,才会在视图中显示对$ scope.dynamic的更新。 The same is true for blockUI. blockUI也是如此。 The logs say that it's called right at the beginning of the method, but the view is never upated. 日志说它是在方法开始时立即调用的,但是视图从未更新过。 Any help on this would be fantastic! 任何帮助都太棒了!

This part: 这部分:

//a lot of work is done here, takes between 2 and 20 Seconds
for(var i = 1; i <= 100; i++){
    $scope.dynamic += 1;
}

Is synchronous code and won't update the view until it's done. 是同步代码,在完成之前不会更新视图。 Basically, the loop updates $scope.dynamic from 1 to 100, but the view can't change until it's done with that; 基本上,循环将$scope.dynamic从1更新$scope.dynamic 100,但是视图必须完成后才能更改; so you just see it at 1, then at 100. 所以您只看到1,然后看到100。

You need to have the work done asynchronously to allow the view to be updated while the work is happening. 您需要异步完成工作,以便在工作进行时更新视图。

How best to go about doing that is another question. 如何最好地做到这一点是另一个问题。 You could use $q in AngularJS to do it. 您可以在AngularJS中使用$q来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM