AngularJs

时间:2016-04-13 13:40:56

标签: angularjs angularjs-filter

我有一个看起来像这样的对象:

{HospitalName: "hospital name", DoctorDetails: {Name: "doctor name"}}

我正在使用ng-repeat迭代这些对象的列表。同时,我使用OR逻辑应用两个过滤器,使其中至少有一个应该返回一个匹配项(如果有的话)。

<input type="text" ng-model="searchQuery" placeholder="Search by hospital or doctor name">

<div  ng-repeat="hospital in list | filter: {HospitalName : searchQuery} || {DoctorDetails : {Name : searchQuery}}">
    <div>{{hospital.HospitalName}}</div>
</div>

但是,只有第一个过滤器被触发。即使有对象具有与搜索查询匹配的医生名称,也不会返回任何匹配项。我出错的任何想法?

我使用这篇文章作为过滤器条件逻辑的参考:Making an Angular Filter Conditional

更新:

我无法弄清楚条件逻辑无法正常工作的原因。因此,考虑到@ Walfrat的建议,我不得不求助于使用自定义过滤器,它完成了工作。如果有人有兴趣,这是我使用的代码:

angular.module('TestApp')
.filter('searchBox', function($filter, $rootScope) {
    return function(input, searchParam) {
        if(input) {
            var searchResults = null;
            //check if a valid search query has been entered
            if(searchParam){
                //use $filter to find hospital names that match query 
                searchResults = $filter('filter')(input,{HospitalName: searchParam});

                //if no hospital names match, fill searchResults with doctor name results(if any) that match query
                //otherwise just append the results to searchResults
                if(searchResults.length == 0){
                  searchResults = $filter('filter')(input,{DoctorDetails : {Name: searchParam}});
                }
                else{
                  angular.forEach($filter('filter')(input,{DoctorDetails : {Name: searchParam}}), function(result){
                    searchResults.push(result);
                  });
                }
                //if there are no doctor or hospital names that match,
                // set searchResult to approprriate message to denote no results found
                if(searchResults.length == 0){
                  searchResults = ["Nothing"];
                }
                return searchResults;
            }
            //console.log(out);
            return input;
        }
        return [];
    }
});

有关更简洁的代码,请参阅@Alex Chance的答案。干杯!

1 个答案:

答案 0 :(得分:1)

在您的情况下,应用自定义过滤器功能可能更容易。

您在ng-repeat中应用过滤器,如此

 <div  ng-repeat="hospital in list | filter:filterFn ">

过滤器功能如下所示:

   $scope.filterFn = function(hospital)
    {
           return hospital.HospitalName.search($scope.searchQuery) != -1 || 
           hospital.DoctorDetails.Name.search($scope.searchQuery) != -1;
    }

这是一个有效的fiddle