加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS ngRepeat未正确更新显示

发布时间:2020-12-17 17:48:22 所属栏目:安全 来源:网络整理
导读:我有一个页面,我使用plupload上传文件,并有一个奇怪的问题,ng-repeat没有正确更新.这是相关代码: div ng:app div name="myForm" ng-controller="Ctrl" input ng-model="test" type="text" /{{test}}div id="container" class="controls" div id="filelist"
我有一个页面,我使用plupload上传文件,并有一个奇怪的问题,ng-repeat没有正确更新.这是相关代码:

<div ng:app>
  <div name="myForm" ng-controller="Ctrl">
    <input ng-model="test" type="text" />{{test}}<div id="container" class="controls">
    <div id="filelist">
      <div ng-repeat="file in filesToUpload">{{file.name}} ({{file.size}}) <b>{{file.percent}}</b></div>
      </div>
      <br />
      <a id="pickfiles" href="#">[Select files]</a>
    </div>
  </div>
</div>?

function Ctrl($scope) {
    $scope.test = '';$scope.filesToUpload = [{id: 1,name: 'test',size: '123kb'}];

    $scope.addItem = function(object) {
        $scope.filesToUpload.push(object);
    }

    $scope.uploader = new plupload.Uploader({
        runtimes : 'html5,flash,browserplus,gears',browse_button : 'pickfiles',container : 'container',max_file_size : '10mb',url : 'upload.php',flash_swf_url : '/plupload/js/plupload.flash.swf'
    });

    $scope.uploader.init();

    $scope.uploader.bind('FilesAdded',function(up,files) {
        $scope.filesToUpload = [];
        $.each(files,function(i,file) {
            $scope.addItem({
                id: file.id,name: file.name,size: plupload.formatSize(file.size)
            });
        });

        console.log($scope.filesToUpload);

        up.refresh(); // Reposition Flash/Silverlight
    });
}?

这是一个精简的jsfiddle显示问题发生:

http://jsfiddle.net/9HuUC/

要重现此问题,请执行以下操作:

>单击[选择文件]并选择几个文件(注意如何在输出的任何位置看不到文件)
>在输入框中输入任何字符(神奇地显示您选择的文件)

什么会导致这种行为?我的意思是我知道数据在$scope.filesToUpload中正确设置,因为我在那里有console.log()甚至在Batarang中检查它并且它在那里很好但是由于某些原因需要更新显示器的其他内容要被更新.

有趣的是,我有另一个ng-repeat在同一页面上工作正常.我想知道它是否与代码的位置有关(在上传者的FilesAdded事件中).

解决方法

问题是由于FilesAdded回调在AngularJS范围之外执行(由上传程序调用),因此不会触发范围更新.

要解决这个问题,只需在回调中添加$scope.$apply调用,封装现有代码:

$scope.uploader.bind('FilesAdded',files) {
    $scope.$apply( function() {
        $scope.filesToUpload = [];
        $.each(files,size: plupload.formatSize(file.size)
            });
        });

        console.log($scope.filesToUpload);

        up.refresh(); // Reposition Flash/Silverlight
    });
});

有了这个更新,它正在努力工作.供参考,请参阅AngularJS官方文档,范围对象的$apply方法:
http://docs.angularjs.org/api/ng. $rootScope.Scope

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读