【问题标题】:AngularJS: How to ignore null values while filtering?AngularJS:过滤时如何忽略空值?
【发布时间】:2018-08-17 19:05:47
【问题描述】:

我正在尝试过滤instructor_name,但是这个表有很多空值,我应该如何忽略那些空字段并仅从不为空的字段中搜索/过滤

 filter:

 `item.instructor_name.toLowerCase().indexOf($scope.courses_search.toLowerCase()) != -1`

因为有很多字段是空的,所以我得到一个错误

TypeError: 无法读取 null 的属性“instructor_name”

$scope.livesearch = function(item) {
    if ($scope.courses_search == undefined) {
        return true;
    } else {
        if (item.subject_cd.toLowerCase().indexOf($scope.courses_search.toLowerCase()) != -1 ||

            item.acad_group.toLowerCase().indexOf($scope.courses_search.toLowerCase()) != -1) {
            return true;
        }
    }

}

$scope.filterFunc = function() {
    return function(item) {

        if (item !== null && typeof item.class_instructor_name !== 'undefined') {
            return item.class_instructor_name.toLowerCase().indexOf($scope.courses_search.toLowerCase()) != -1;
        }
        return false;
    };
};

【问题讨论】:

    标签: angularjs angularjs-filter


    【解决方案1】:

    您正在将 item 与 null 进行比较,但如果 item 未定义,则将进行下一次验证,因为 (undefined !== null),因此它将尝试在 undefined 上查找instructor_name,这显然不起作用。

    AngularJS 有它自己的检查器,angular.isDefined() 和 angular.isUndefined()。您可以使用其中之一,或进行稍微不同的检查,例如:

    if (item && item.instructor_name) ...
    

    如果您使用的是 lodash,您可以简单地执行以下操作: if (_.get(item, 'instructor_name')) ...

    【讨论】:

      【解决方案2】:

      一种选择是在控制器上添加过滤器并从那里处理空检查。 请记住在应用 toLowerCase() 方法之前检查该值是否已定义。

      $scope.filterFunc = function() {
        return function(item) {
          if (typeof $scope.courses_search !== 'undefined' && item !== null) {
              if(typeof item.subject_cd !== 'undefined'){
                  return item.subject_cd.toLowerCase().indexOf($scope.courses_search.toLowerCase()) != -1;
              }
              if(typeof item.acad_group !== 'undefined'){
                  return item.acad_group.toLowerCase().indexOf($scope.courses_search.toLowerCase()) != -1;
              }
          }
          return false;
        };
      };
      

      然后在视图中

      ng-repeat="item in items | filter:filterFunc"
      

      【讨论】:

      • 如果我这样做,我会收到错误TypeError: Cannot read property 'toLowerCase' of undefined
      • 遇到同样的错误TypeError: Cannot read property 'toLowerCase' of undefined
      • 您的回答并没有帮助它仍然显示错误TypeError: Cannot read property 'toLowerCase' of undefined
      • @JKLM 更新了答案。请注意,如果您添加更多要过滤的值,则需要在应用 toLowerCase() 之前检查该值是否已定义
      猜你喜欢
      • 1970-01-01
      • 2016-04-21
      • 2021-01-01
      • 2020-06-05
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多