带角度滤波器或带有角度的滤波器

时间:2017-10-11 12:51:42

标签: javascript angularjs arrays filter

使用角度过滤器过滤javascript数组时,语法为

$ filter('filter')(数组,表达式,比较器,anyPropertyKey)

根据角度文档,第二个参数表达式可以采用

  

用于过滤对象的特定属性的模式对象   包含在数组中。例如{name:“M”,phone:“1”}谓词将   返回一个属性名称包含“M”和的项目数组   物业电话包含“1”

在上面提到的例子中我们得到的条件是名称匹配“M”手机匹配“1”

但如何实现条件匹配“M”手机匹配“1”

代码示例

var employees=[
  {lastname:"john",firstname:"jack",age:40,sex:"m"},
  {lastname:"Abby",firstname:"john",age:20,sex:"f"},
  ];

var filteredData =$filter('filter')(employees,{firstname:'john', lastname:'john'});

这导致没有记录,因此被应用 我们可以尝试将姓氏或名字的记录过滤为“john”

这可以通过使用自定义过滤器来实现

1 个答案:

答案 0 :(得分:0)

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

myApp.controller('myCtrl', ['$scope', '$filter', function($scope, $filter){

  var employees=[
  {lastname:"john",firstname:"jack",age:40,sex:"m"},
  {lastname:"Abby",firstname:"john",age:20,sex:"f"},
  {lastname:"Abby",firstname:"mark",age:20,sex:"f"},
  ];
  
$scope.filteredData = $filter('filter')(employees, function(value){
        return value.firstname == 'john' || value.lastname == 'john';
});

console.log($scope.filteredData);
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!DOCTYPE html>
<html ng-app="myApp">

<body>

  <div ng-controller="myCtrl">
    {{filteredData}}
  </div>


</body>

</html>

你可以使用如下。

$scope.filteredData = $filter('filter')(employees, function(value){
        return value.firstname == 'john' || value.lastname == 'john';
});