Search code examples
angularjsangularjs-ng-repeatng-flow

ng-flow upload file - how to add to TOP of ng-repeat list


I'm using the angular ng-flow component for file upload and it's working great besides a few nuances. I'd love to be able to have the new files that I try to upload put on the top of the list rather than on the bottom of the list so it's clear for users the latest one that has been uploaded. I tried using the angular order by command but that doesn't seem to work unless it's an existing list compared to adding a new file to the list.

Basically I create a new row for each file once it's complete and print out the file details:

<tr ng-repeat="file in $flow.files | orderBy:'file.name'" ng-hide="file.isComplete()">

the list looks like this before upload:

old1
old2
old3

then I add a new file and I see:

old1
old2
old3
new1

when I'd like:

new1
old1
old2
old3

This is probably more of a question about using Angular's ng-repeat functionality for new items added to the list.


Solution

  • To use orderBy filter, you need just let the property in filter, as the following:

    <tr ng-repeat="file in $flow.files | orderBy: 'name'" ng-hide="file.isComplete()">
    

    EDIT

    Since you want to sort your items by chronological order, it should give you the expected result:

    <tr ng-repeat="file in files | orderBy: '$index': true">
    

    Here's is a snippet working:

    var app = angular.module('app', []);
    
    app.controller('mainCtrl', function($scope) {
      $scope.files = [  
         {  
            "id":1,
            "name":"Old1"
         },
         {  
            "id":2,
            "name":"Old2"
         },
         {  
            "id":3,
            "name":"Old3"
         }
      ];
    
      var increment = 1;
      $scope.push = function (name) {
        $scope.files.push({ "id": increment + 3, "name": name + increment++ })
      }
    });
    <!DOCTYPE html>
    <html ng-app="app">
    
    <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>      
    </head>
    
    <body ng-controller="mainCtrl">
    <p>Before Filter:
    <table>
      <tr ng-repeat="file in files">
        <td ng-bind="file.name"></td>
      </tr>
    </table>
    <hr />
    <p>After Filter:
    <table>
      <tr ng-repeat="file in files | orderBy: '$index': true">
        <td ng-bind="file.name"></td>
      </tr>
    </table>
    <hr>
    <button type="button" ng-click="push('New')">Add new file</button>
    </body>
    
    </html>