AngularJS orderby with empty field

前端 未结 9 1752
北海茫月
北海茫月 2020-12-05 13:19

I am ordering a my data and its working all correcty except some fields are empty or have no value. When ordered these empty field come up first. For example when ordering n

9条回答
  •  攒了一身酷
    2020-12-05 14:00

    @Klaster_1 was really on to something but as soon as I needed a nested value the filter stopped working. Also, if I was reverse ordering I still wanted my null values to show up before 0. I added $parse to take care of the nested keys and added a reverse parameter to I knew when to put the null values at the top.

    .filter("emptyToEnd", function ($parse) {
        return function (array, key, reverse) {
            if(!angular.isArray(array)) return;
            var keyFn = $parse(key);
            var present = [];
            var empty = [];
    
            angular.forEach(array, function(item){
              var val = keyFn(item);
              if(angular.isUndefined(val) || val === null) {
                empty.push(item);
              } else {
                present.push(item);
              }
            });
    
            if (reverse) {
              return present.concat(empty);
            } else {
              return empty.concat(present);
            }
        };
    });
    

提交回复
热议问题