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>
价格:<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>