2012-10-31 130 views
4

我有一个页面,我正在使用plupload上传文件和有一个奇怪的问题与ng-repeat没有正确更新。下面是相关代码:AngularJS ngRepeat没有更新显示正确

<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/

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

  1. 点击[选择文件]并选择几个文件(请注意,您看不到输出上任何位置显示的文件)
  2. 在输入框中键入任何字符(神奇地显示您选择的文件)

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

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

+0

我认为你有一个额外的密切div标签的NG-重复后 – qualidafial

回答

8

这个问题是由于FilesAdded回调在AngularJS范围之外执行(它被上传者调用),因此范围更新不会被触发。

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

$scope.uploader.bind('FilesAdded', function(up, files) { 
    $scope.$apply(function() { 
     $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 
    }); 
}); 

安装此更新,它的工作的小提琴。作为参考看到AngularJS官方文档$应用范围对象方法: http://docs.angularjs.org/api/ng $ rootScope.Scope

+0

谢谢你,我。将不得不阅读。 – ryanzec