0

I have an array of users, I want to have my ng-repeat ordered by last name when first loaded. After a new user is added have the ng-repeat ordered by dated added then last name. Essentially I want the newest users pushed to the top of the ng-repeat.

<th ng-click="menuFilter('lastName', 1);">
  <div ng-class='{"menuSort":sortColumn==1}'>Name <span ng-show="share.orderByField == 'lastName'">
  </div>
</th>

 <tr ng-repeat="user in users | orderBy:orderByField:reverseSort"></tr>

In my JS...

_this.sortColumn = 1;
_this.orderByField = 'lastName';
_this.reverseSort = false;

 _this.menuFilter = function(section, column) {
      _this.orderByField = section;
      _this.reverseSort = !_this.reverseSort;
      _this.sortColumn = column;
};

//my attempt to reset the order by created at date
if( _this.isRefreshing ) { 
        _this.orderByField = ['createdAt', 'lastName'];
}

Basically this code is not doing anything. I think I am missing a step in the HTML.

Thanks!

user1876246
  • 1,219
  • 5
  • 18
  • 33

2 Answers2

0

I think this is easiest done by sorting the array in pure javascript and then using a ng-repeat without the orderBy attribute.

HTML:

<div ng-repeat="user in users">{{user}}</div>

<input type="text" ng-model="name"></input>
<button ng-click="addName()">Add name</button>

JS:

$scope.users = ["Rusty", "Shackleford", "Dale", "Gribble"];
$scope.users.sort();

$scope.addName = function() {
   $scope.users.unshift($scope.name);
}

JSFiddle: http://jsfiddle.net/asWF9/2/

This answer may help to sort your array: https://stackoverflow.com/a/6712080/3675149

Community
  • 1
  • 1
Rusty
  • 329
  • 1
  • 8
0

Try using "unshift" instead of 'push' to add an item into the array. The unshift in js enables us to insert an item to the top of an array.

Alagarasan M
  • 907
  • 8
  • 16