7

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
    }
}        
krv
  • 2,830
  • 7
  • 40
  • 79

3 Answers3

7

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.

Behrooz
  • 1,895
  • 4
  • 31
  • 47
  • i am getting the data form a database so it will be hard to do so..isn't there any other custom function that i can use? – krv Sep 03 '15 at 15:18
  • You can create a custom angular filter that handles the sorting. Then you could just use:
  • {{ whatever}}
  • but I would say that is harder. I think in your angular code when you fetch the data, just write a loop that adds the "pinned" variable to every item. Really doesn't look so hard. – Behrooz Sep 03 '15 at 15:21
  • 1
    Since this is javascript you don't even need to include pinned:false on the other objects, a attribute not present counts as false. – Alex Oct 19 '16 at 00:22