黑马程序员技术交流社区
标题:
【上海校区】Angularjs过滤器
[打印本页]
作者:
梦缠绕的时候
时间:
2018-7-24 09:46
标题:
【上海校区】Angularjs过滤器
1.内置过滤器 (1)货币过滤器 currency <span ng-bind="price | currency:'人民币¥'"></span> (2)日期时间过滤器 <span ng-bind="date | date:'yyyy年MM月dd日 hh:mm:ss'"></span> (3)json过滤器 <span ng-bind="users|json"></span> (4)filter 过滤输出(从数组项中选择一个子集) $scope.names = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'} ]; <input type="text" ng-model="test"> <li ng-repeat="x in names | filter:test"></li> (5)lowercase格式化字符串为小写 uppercase格式化字符串为大写 <li ng-repeat="x in names"> {{ (x.name | uppercase) + ', ' + x.country }} </li> (6)orderBy 根据某个表达式排列数组 <li ng-repeat="x in names | orderBy:'country'"></li>2.自定义过滤器结构: {{待过滤数据 | 过滤器名:参数1:参数2:参数3.....}} app.filter('过滤器名', function () { return function (待过滤数据, 参数....) { ...... return 已过滤数据; }Demo1:筛选出某个数组
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="angular.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<!-- 这里是使用angularjs内置的filter 筛选出苹果-->
<ul>
<li ng-repeat="x in products | filter:'苹果'">{{x.name}}</li>
</ul>
<!-- 这里使用自定filterprice 筛选出价格小于9的水果名字 -->
<ul>
<li ng-repeat="x in products | filterprice:9">{{x.name}}</li>
</ul>
</div>
<script>
var
app = angular.module(
'myApp'
, []);
app.controller(
"myCtrl"
, [
"$scope"
, function ($scope) {
$scope.products = [
{
name
:
"苹果"
,
price
:
"5"
,
counts
: 24},
{
name
:
"香蕉"
,
price
:
"2.5"
,
counts
: 27},
{
name
:
"橘子"
,
price
:
"6"
,
counts
: 28},
{
name
:
"葡萄"
,
price
:
"10"
,
counts
: 23}
];
}]);
//筛选出价格小于某个数的水果
app.filter(
'filterprice'
, function () {
return
function (e,price) {
var
newarr = [];
angular.forEach(e, function(val,index){
if
(val.price < price){
newarr.push(val);
}
});
return
newarr;
}
})
</script>
</body>
</html>
运行结果:
Demo2:自定义百分比转换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="angular.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
原始数据<input type="text" ng-model="input">
<p>转换结果:{{input | percent:100:1}}</p>
</div>
<script>
var
app = angular.module(
'myApp'
, []);
app.controller(
"myCtrl"
, [
"$scope"
, function ($scope) {
}]);
// 转为百分比
app.filter(
'percent'
, function () {
return
function (numerator, denominator) {
//参数传入:分子和分母
if
(numerator ===
''
|| numerator ===
undefined
|| numerator ===
'unknown'
) {
// 无数据
return
'--'
;
}
if
(denominator !==
undefined
&& denominator !== 0) {
return
(numerator / denominator * 100) +
'%'
;
}
};
});
</script>
</body>
</html>
运行结果:
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2