Вопрос

I have a list of employees and there is a field called mobile, which has a value of true or false. I want to be able to do a $filter('orderBy') on this "mobile" field using angularJS. For example, I want to be able to filter the list of employees where all the employees that have the "mobile" field set to true to appear at the top of the list.

I do NOT want to do this in the ng-repeat. I want to do this inside my code for various reasons. Anyway, I have the following code, but the employees that have the "mobile" field set to true is NOT appearing on top of the list as I would like. Can you please tell me how I can achieve this using $filter('orderBy') method?

Here are the code:

col = "mobile";
$scope.employees = $filter('orderBy')($scope.employees, col);
Это было полезно?

Решение

False values are less than true values in Javascript (0 < 1); that's why employees with mobile = false come first after you have them sorted by that property.

So in order to accomplish what you want, you just need to change the sort order in orderBy by prefixing the property name with a - (dash):

$scope.employees = $filter('orderBy')($scope.employees, '-mobile');

Working plunk here.

You can find more information on the documentation about the orderBy filter.

Другие советы

I think this is what you are looking for: http://jsfiddle.net/Sg9YY/

Because you don't want the filter in the ng-repeat, you need to provide filtered contacts:

$scope.filteredEmployees=angular.copy($scope.employees);

Then you can watch for whatever event, and then apply the filter in the controller:

$scope.$watch('sort',function(){
    if($scope.sort=='none'){
        $scope.filteredEmployees=angular.copy($scope.employees);
    }else{
        $scope.filteredEmployees=$filter('orderBy')($scope.employees,'myVar',$scope.sort);
    }
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top