如何使用OR作为条件过滤多个列时使用$ filter('filter')?

时间:2016-09-28 13:24:00

标签: javascript angularjs angular-filters

我在AngularJs Application中有一系列客户

var customers = [
    {
        "Name": "Alfreds Futterkiste",
        "City": "Berlin",
        "Country": "Germany"
    },
    {
        "Name": "Ana Trujillo Emparedados y helados",
        "City": "México D.F.",
        "Country": "Mexico"
    }
];

我的问题是如何使用多列进行过滤。我尝试了下面的代码,它不起作用。

$scope.customers = (
    $filter('filter')(customers, {
        Name: $scope.criteria.searchtext,
        City: $scope.criteria.searchtext
    })
);

修改

如何将上述语法转换为'或'请检查Sample以获取参考。

3 个答案:

答案 0 :(得分:0)

由于您没有使用自定义角度过滤器,我通常只使用Array.prototype.filter(),尽管您也可以使用$filter的函数参数

以下假定部分匹配

$scope.customers =  customers.filter(item){
     var term = $scope.criteria.searchtext.toLowerCase();
     //partial match 
     return item.Name.toLowerCase().indexOf(term) >-1 
            || item.City.toLowerCase().indexOf(term) >-1;

});

这可以很快变成角度自定义滤镜,也可以在视图中使用

答案 1 :(得分:0)

在客户中添加过滤器

<tr class="animate" ng-repeat="customer in customers | filter: criteria.searchtext">
<td ng-bind="customer.Name"></td>
<td ng-bind="customer.City"></td>
<td ng-bind="customer.Country"></td>
</tr>

然后将客户移至$scope,如下所示

$scope.customers = [{}]; // Will be array of customers

选中此Solution

请告诉我们这是否适合您。

答案 2 :(得分:-1)

我创建了一个新的自定义过滤器,使用;WITH T AS ( SELECT U.UserID, U.Name, CASE WHEN R.WorkItem LIKE 'IR%' THEN R.WorkItem ELSE '' END AS IRCode, CASE WHEN R.WorkItem LIKE 'SR%' THEN R.WorkItem ELSE '' END AS SRCode FROM @tblUser U INNER JOIN @tblRelationship R ON U.UserId=R.UserId ) SELECT Name, SUM(CASE IRCode WHEN '' THEN 0 ELSE 1 END) AS 'IR Count', SUM(CASE SRCode WHEN '' THEN 0 ELSE 1 END) AS 'SR Count' FROM T WHERE ( (T.IRCode='' OR T.SRCode='') AND ( T.IRCode IN (SELECT ID FROM @tblIR WHERE Status='Active') OR T.SRCode IN (SELECT ID FROM @tblSR WHERE Status='Active') ) ) GROUP BY T.Name 条件过滤多个列,

OR
var myApp = angular.module('myApp',[]);

function MyCtrl($scope,myFilterFilter) {
	 $scope.criteria = {};
  $scope.criteria.searchtext = 'Berlin';
		var customers =[{"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"},
{"Name":"Ana Trujillo Emparedados y helados","City":"México D.F.","Country":"Mexico"},{"Name":"Futterkiste","City":"Berlin","Country":"Germany asfdasdas"}]
$scope.customers=myFilterFilter(customers,$scope.criteria.searchtext,$scope.criteria.searchtext);
 
}


angular.module('myApp').filter('myFilter', function() {
  return function(customers,name,city) {
      var yes = [];
      angular.forEach(customers, function(value, key) {
        if ((value['Name'] === name) || (value['City'] === city)) {
           yes.push(value);              
        }
        
    });
    console.log(yes)
    return yes
  }
})

Here is the fiddle