# 自定义过滤器

两种方式

* module.filter(name, filterFactory)
* @$filterProvider.register().

**例子：** index.html

```markup
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<div ng-app="myApp">

    <div ng-controller="firstController">
        <p>filterAge:</p>
        <ul>
            <li ng-repeat="user in data | filterAge">
                {{user.name}}
                {{user.age}}
                {{user.city}}
            </li>
        </ul>
        <p>filterCity:</p>
        <ul>
            <li ng-repeat="user in data | filterCity">
                {{user.name}}
                {{user.age}}
                {{user.city}}
            </li>
        </ul>
    </div>
</div>


<script src="//cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
<script type="text/javascript" src="app/index.js"></script>


</body>
</html>
```

app/index.js

```javascript
var myApp = angular.module('myApp', [], function ($filterProvider, $provide, $controllerProvider) {

    $provide.service('Data', function () {
        return [
            {
                name: '张三',
                age: '20',
                city: '上海'
            },
            {
                name: '李四',
                age: '30',
                city: '北京'
            }
        ];

    });
    //$filterProvider.register方式
    $filterProvider.register('filterAge', function () {
        return function (obj) {
            var newObj = [];

            angular.forEach(obj, function (o) {
                if (o.age > 20) {
                    newObj.push(o);
                }
            });

            return newObj;

        }
    });


    $controllerProvider.register('firstController', function ($scope, Data) {
        $scope.data = Data;
    })
})

// module.filter方式
.filter('filterCity',function(){
    return function(obj){
        var newObj = [];

        angular.forEach(obj, function (o) {
            if (o.city === '上海') {
                newObj.push(o);
            }
        });

        return newObj;
    }
})
```

**效果：**

![](/files/-LfnTGcp_DYZKJ2gaqt3)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/angularjs/filters/zi_ding_yi_guo_lv_qi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
