angular: filter过滤器

HTML模板绑定符号{{}}内,通过 | 符号来调用过滤器。如:

{{name | filter }}

在JavaScript中通过$filter来调用过滤器。

也可以多个filter连用,上一个filter的输出将作为下一个filter的输入。

{{ expression | filter1 | filter2 | ... }}
 
filter还可以接收参数。

以html形式使用过滤器时,如需传递参数给过滤器,只要在过滤器名字后面加冒号即可。多个参数,可以在每个参数后面加入冒号。

filter过滤器可以从给定数组中选择一个子集,并且将其生成一个新数组返回。filter过滤器只能用于数组。

这个过滤器,它的第一个参数可以是字符串、对象、(用来从数组中选择元素的)函数。第二个参数可以是true、false、函数。

The filter filter can only be used on arrays, and it returns an array containing only the matching items.

第一个参数是expression,它可以是:

1. 字符串 、或者 !字符串 - 分别表示包含或者不包含这个字符串的元素。

{{['Ari', 'likes', 'to', 'travel']| filter:'i'}}

输出:["Ari","likes"]

2. 对象:将待过滤对象(| 符号前面的数组)的属性和这个对象中的同名属性进行比较,如果属性值是字符串就会判断是否包含该字符串。如果希望全部属性进行对比,可以将$作为键名。

{{[{
    'name':'Ari',
    'city':'Beijing'
},{
    'name':'Nate',
    'city':'Xiamen'
}] | filter:{'city':'Beijing'} }} 

输出:[{"name":"Ari","city":"Beijing"}] 

3. 函数 function(value, index, array):布尔值函数会对(给定数组的)每个元素执行这个函数,返回非假值的元素会出现在新的数组并返回。

第二个参数是比较器,它可以是:(默认值为false)

1. true

2. false

3. 函数(布尔函数)

先来看一个例子

比如以下这段代码,这里的true产生了什么样的作用?

<body ng-app="myFilterApp">

<div ng-controller="myFilterController">
    <table id="searchTextResults">
        <tr><th>Name</th><th>Phone</th></tr>
        <tr ng-repeat="friend in friends |myFilter:'param1':'param2':true:'windowScopedFilter'">
            <td>{{friend.name}}</td>
            <td>{{friend.phone}}</td>
        </tr>
    </table>
</div>

<script>
    function windowScopedFilter(input) {
        var output = [];
      
//[].forEach方法中的function回调有三个参数:第一个参数是遍历的数组内容,第二个参数是对应的数组索引,第三个参数是数组本身

  //angular.forEach(objs, function(data,index,array){} objs - 需要遍历的集合

        angular.forEach(input, function (v,k) {
            if(v.phone.indexOf('555')>= 0){
                output.push(v);
            }
        });
        return output;
    }
    var myapp = angular.module('myFilterApp', []);
    myapp.filter('myFilter', function () {
        return function (input, param1) {
            var args = Array.prototype.slice.call(arguments);//将具有length属性的对象转成数组
            if (5<=args.length) {
                return window[args[4]](input);
            }
            return input;
        }
    });
    myapp.controller('myFilterController', ['$scope', function ($scope) {
        $scope.friends = [
            {name:'John', phone:'555-1276'},
            {name:'Annie', phone:'800-BIG-MARY'},
            {name:'Mike', phone:'555-4321'},
            {name:'Adam', phone:'555-5678'},
            {name:'David', phone:'555-8765'},
            {name:'Mikay', phone:'555-5678'}
        ];
    }]);

</script>

让我们来翻一翻官方文档吧。filter 

在html模板绑定:

{{ filter_expression | filter : expression : comparator : anyPropertyKey}}

可以看出,第二个参数是一个比较器。比较器比较什么?让我们继续看原文:

Comparator which is used in determining if values retrieved using expression (when it is not a function) should be considered a match based on the the expected value (from the filter expression) and actual value (from the object in the array).

Can be one of:

  • function(actual, expected): The function will be given the object value and the predicate value to compare and should return true if both values should be considered equal.

  • true: A shorthand for function(actual, expected) { return angular.equals(actual, expected)}. This is essentially strict comparison of expected and actual.

  • false: A short hand for a function which will look for a substring match in a case insensitive way. Primitive values are converted to strings. Objects are not compared against primitives, unless they have a custom toString method (e.g. Date objects).

Defaults to false.

先试着翻译下这段。

比较器,用于确定是否使用表达式检索值(当比较器不是函数时),对预期值(过滤器表达式)和给定的实际值(数组中的对象)进行比较。

它可以是:

1. 函数 function(actual, expected): 该函数接受两个参数对象值和预期值进行比较,如果这两个值应被视为相等,应返回TRUE。(不敢怀疑英文原文文档英文拼写错误,但是怎么看都应该是predicted value 预期值吧~)

2. true: function(actual, expected) { return angular.equals(actual, expected)}的缩写形式。对预期值和实际值进行严格比较。

3. false:对子字符串不分大小写的匹配。原始值被转换为字符串。对象如果没有自定义的toString方法,则不和原始值进行比较。

默认值为false。

实际上,看完官方文档,对于这个比较器的理解和应用,感觉不是那么明朗。这就需要靠多看一些例子来理解。

 

结合ng-model, filter过滤器还有一个超赞的功能:

<div ng-app="myApp" ng-controller="namesCtrl">

<p>输入字母:</p>

<p><input type="text" ng-model="test"></p>

<ul>
  <li ng-repeat="x in names | filter:test">
    {{ x }}
  </li>
</ul>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
});
</script>

<p>列表只包含匹配过滤器的名称。</p>

效果如下:

输入字母,就可以过滤出只包含输入字母的项。

原文地址:https://www.cnblogs.com/dodocie/p/6836572.html