angularjs 自定义过滤器 v1.x

AngularJS 过滤器

过滤器可以使用一个管道字符(|)添加到表达式和指令中。

过滤器描述
currency格式化数字为货币格式。
filter从数组项中选择一个子集。
lowercase格式化字符串为小写。
orderBy根据某个表达式排列数组。
uppercase格式化字符串为大写。

AngularJS 过滤器可用于转换数据,以上过滤器是angularjs自带的,通常不能满足我们的特殊需要,因此,通常还需要懂得自定义过滤器。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>angularjs 自定义过滤器</title>
</head>
<body ng-app="app">
<div ng-controller="ctr">
    <h1>水果价格表</h1>
    <div>
        价格范围:
        <input type="number" ng-model="min">--
        <input type="number" ng-model="max">
    </div>
    <ul>
        <!--自定义过滤器myfilter在html中调用时不需要传第一个参数,后面2个参数用“:”拼接,可以是字符串、数值或者变量-->
        <li ng-repeat="item in fruits | myfilter:min:max">
            名称:<span ng-bind="item.name"></span>&nbsp;&nbsp;&nbsp;&nbsp;
            价格:<span ng-bind="item.price"></span>
        </li>
    </ul>

</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
    angular.module('app', [])
            .filter('myfilter', function () {
                return function (fruits, min, max) {
                    //fruits 为第一个参数,即待过滤的数组
                    //min,max为其他参数可有可无
                    var arr = [];
                    min = min > 0 ? min : 0;
                    max = max ? max : 99999999;
                    angular.forEach(fruits, function (item) {
                        if (item.price > min && item.price <= max) {
                            arr.push(item);
                        }
                    });
                    return arr;
                }
            })
            .controller('ctr', ['$scope', '$filter', function ($scope, $filter) {
                $scope.fruits = [
                    {name: 'apple', price: 5.2},
                    {name: 'banana', price: 3.5},
                    {name: 'mango', price: 12},
                    {name: 'watermelon', price: 2.5},
                    {name: 'peach', price: 4},
                    {name: 'grape', price: 15},
                    {name: 'litchi', price: 20},
                    {name: 'orange', price: 6}
                ];

                //自定义过滤器myfilter在js中使用时,案例如下:
                //第一个参数是待过滤数据,第2,3个数据是根据定义要求传入的数据,用逗号分割
                $scope.res = $filter('myfilter')($scope.fruits, 10, 20);
                console.log($scope.res);
            }])
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值