AngularJS ngRepeat Does not refresh display properly

I have a page where I use plupload to download files and has a weird problem when ng-repeat is not updating properly. Here is the relevant code:

<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 }); }​ 

Here is a stripped down jsfiddle showing the problem:

http://jsfiddle.net/9HuUC/

To reproduce this problem, follow these steps:

  • Press [select files] and select several files (note how you don’t see files displayed anywhere on the output)
  • Enter any character in the input field (the magic files that you selected, you know)

What can cause this type of behavior? I mean, I know that the data is set correctly in $ scope.filesToUpload, because I have console.log () and even checked it in Batarang and it works well there, but for some reason I need that Something else to update to display for the update.

Interestingly, I have another ng-repeat that works fine on one page. I am wondering if it has anything to do with where the code is (being inside the FilesAdded event on the bootloader).

+4
source share
1 answer

The problem is that the FilesAdded callback is executed outside the scope of AngularJS (it is called by the loader), so the scope updates will not start.

To solve this problem, simply add a call to $scope.$apply in the callback, encapsulating the existing code:

 $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 }); }); 

With this update, he works in the violin. For help, see the official AngularJS documentation, $ apply the scope object method: http://docs.angularjs.org/api/ng . $ rootScope.Scope

+8
source

All Articles