AngularJS orderby : keep an element of array on to

2019-07-14 18:08发布

问题:

I have searched and don't found an answer to my question. Hope, I've well searched ! So, this is my problem :

<div id="{{expression.comment_id.$id}}" class="comments" ng-repeat="expression in expressions| orderBy:orderProp"

So, orderBy works great, but I have a specific need : expression.comment_id with '0' id must stay on top.

How can do this ? I think I must use a personnal filter but I'm not sure this is the more efficient solution. If this is a good way, how can I implement it correctly ?

Thanks for your help !

回答1:

here you go made a fiddle for you: http://jsfiddle.net/sameersemna/81q9jwg9/

basically you have to make a custom orderBy filter:

<ul ng-repeat="expression in expressions | orderBy:myValueFunction">

in the controller:

$scope.myValueFunction = function(expression) {
        if(expression.comment_id == 0){
            return expression.comment_id;
        }else{
            return expression.orderProp;
        }
    }