Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat orderBy keeping fixed top value

see the fiddle here http://jsfiddle.net/prantikv/gcz4gwgw/1/

i want to get one i item on the top of the list and the rest in alphabetical order:

<div ng-controller="MyCtrl">
 <ul>
  <li ng-repeat="value in name | orderBy:'name'">{{value.name}} </li>   
   </ul>    

  </div>

In my controller i have the following

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.name=[
{name:'zani',country:'Norway'},
{name:'aege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]


}

what i want is the name "kai" to come first and then the rest in alphabetical order.

================Edit===============

now i have played and got the following

in my view:

<div ng-controller="MyCtrl">
 <ul>
  <li ng-repeat="value in name | orderBy:myValueFunction ">{{value.name}} </li>   
   </ul>    

  </div>

in my controller :

 $scope.myValueFunction = function(value) {
    if(value.name == "kai"){

        return value.name;
    }else{
        //what todo here so the rest of the list is sorted alphabetically
    }
}        
like image 318
krv Avatar asked Sep 03 '15 15:09

krv


2 Answers

You can add a "pinned" variable to your array item, and make it like this:

$scope.name=[
{name:'zani',country:'Norway', pinned: false},
{name:'aege',country:'Sweden', pinned: false},
{name:'Kai',country:'Denmark', pinned: true}]

And then change you ng-repeat accordingly:

<li ng-repeat="value in name | orderBy:['pinned','name']">{{value.name}} </li>

Now as "pinned" has the first order priority, 'kai' will always be the first in the loop.

like image 150
Behrooz Avatar answered Oct 03 '22 16:10

Behrooz


Above answer is good to implement but as you don't have an option to edit a response then you follow easy workaround like I mentioned below. Else you could go for creating custom filter.

Markup

<div ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="single in name | filter:{'name':'Kai'}">{{single.name}} </li>  
    <li ng-repeat="value in name | filter:{'name':'!Kai'}" | orderBy:'name'">{{value.name}} </li>   
  </ul>    
</div>
like image 44
Pankaj Parkar Avatar answered Oct 03 '22 15:10

Pankaj Parkar