【问题标题】:How to filter a boolean value using $filter('orderBy')如何使用 $filter('orderBy') 过滤布尔值
【发布时间】:2014-05-11 04:31:47
【问题描述】:

我有一个员工列表,其中有一个名为 mobile 的字段,其值为 true 或 false。我希望能够使用 angularJS 在这个“移动”字段上做一个$filter('orderBy')。例如,我希望能够过滤所有将“移动”字段设置为true 的员工出现在列表顶部的员工列表。

我不想在ng-repeat 中这样做。出于各种原因,我想在我的代码中执行此操作。无论如何,我有以下代码,但是将“移动”字段设置为true 的员工并没有像我想要的那样出现在列表顶部。你能告诉我如何使用$filter('orderBy') 方法实现这一点吗?

代码如下:

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

【问题讨论】:

    标签: angularjs angularjs-filter angularjs-orderby


    【解决方案1】:

    Javascript 中的假值小于真值 (0 mobile = false 的员工在您按该属性排序后排在第一位。

    所以为了完成你想要的,你只需要改变orderBy中的排序顺序,在属性名称前加上一个-(破折号):

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

    工作狂here

    您可以在documentation 上找到有关orderBy 过滤器的更多信息。

    【讨论】:

      【解决方案2】:

      我想这就是你要找的东西:http://jsfiddle.net/Sg9YY/

      由于您不希望 ng-repeat 中的过滤器,您需要提供过滤后的联系人:

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

      然后你可以观察任何事件,然后在控制器中应用过滤器:

      $scope.$watch('sort',function(){
          if($scope.sort=='none'){
              $scope.filteredEmployees=angular.copy($scope.employees);
          }else{
              $scope.filteredEmployees=$filter('orderBy')($scope.employees,'myVar',$scope.sort);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2020-05-15
        • 1970-01-01
        • 2018-07-03
        • 1970-01-01
        • 2017-06-25
        • 1970-01-01
        • 2019-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多