Karthik
Karthik

Reputation: 470

How to move a particular element in top using orderBy in angular js

I have an array of names

var arr = [
              {firstName : 'King'},
              {firstName :'Auk'},
              {firstName :'Kish'},
              {firstName :'You'},
              {firstName :'Blob'}
          ];

I am using the orderBy of angular js on the firstName field, like so

 <div ng-repeat="name in arr| orderBy: 'firstName'">  
     <p>{{arr.firstName}}</p>// Auk, Blob, King,Kish,You
 </div>

But, I want the 'You' in the first place , is there any mechanism to bring that element to top.

Upvotes: 2

Views: 1531

Answers (4)

oBlissing
oBlissing

Reputation: 68

If you for some reason want to keep your own record in the repeater, add another property called sortPrio or similar. Then sort by firstName and sortPrio.

Upvotes: 0

dfsq
dfsq

Reputation: 193271

You will can write one more simple filtering function that would handle this special behaviour:

<div ng-repeat="name in arr | orderBy:[youSort, 'firstName']">  
    <p>{{name.firstName}}</p>
</div>

where function youSort would be defined as:

$scope.youSort = function(obj) {
    return obj.firstName === 'You' ? '' : name;
};

Here is a demo:

angular.module('demo', []).controller('MainController', function($scope) {
  $scope.arr = [
      {firstName : 'King'},
      {firstName :'Auk'},
      {firstName :'Kish'},
      {firstName :'You'},
      {firstName :'Blob'}
  ];
  $scope.youSort = function(obj) {
      return obj.firstName === 'You' ? '' : name;
  };
});
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>

<div ng-app="demo" ng-controller="MainController">
    <div ng-repeat="name in arr | orderBy:[youSort, 'firstName']">
        <p>{{name.firstName}}</p>
    </div>
</div>

Upvotes: 4

suvroc
suvroc

Reputation: 3062

If you want to apply some custom order to your data, you should order it in your controller.

var elem = $scope.arr.pop()
$scope.arr.unshift(elem);

Upvotes: 0

salezica
salezica

Reputation: 76949

You shouldn't alter sort order to make this exception. Instead, move the special case outside the repetition.

  • Manually include You in your template before the ngRepeat
  • Use filter (or off-template processing) to remove You from the array
  • Pass the other elements through orderBy

If the amount of markup is large, and you don't want to write it all twice for You and ngRepeat, you can create and include a sub-template.

Upvotes: 2

Related Questions