AngularJs基础——过滤器

时间:2022-01-28 15:33:22

AngularJs的过滤器用于转化数据:

1)uppercase——格式化字符串为大写;

2)lowercase——格式化字符串为小写;

3)currency——格式化数字为货币格式;

4)orderBy——根据某个表达式排列数组;

5)filter——从数组项中选择一个子集

<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>Angular基础</title>
</head>
<body>
<div ng-app="myApp">
<!-- 向表达式添加过滤器:可以通过一个管道字符(|)和一个过滤器添加到表达式中-->
<p>将字符串转换为大小写:</p>
<div ng-controller="uppercaseController">
<p>姓名为 {{ person.lastName | uppercase }}</p>
</div>
<div ng-controller="lowercaseController">
<p>姓名为 {{ person.lastName | lowercase }}</p>
</div>

<p>货币过滤:</p>
<div ng-controller="costController">
数量:<input type="number" ng-model="quantity">
价格:<input type="number" ng-model="price">
<p>总价 = {{ (quantity * price) | currency }}</p>
</div>

<!-- 向指令添加过滤器:可以通过一个管道字符(|)和一个过滤器添加到指令中-->
<p>按国家的字母顺序排序对象:</p>
<div ng-controller="namesController">
<p>循环对象:</p>
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<p>按输入的字母显示对象:</p>
<div ng-controller="namesFilterController">
<p>输入过滤:</p>
<p><input type="text" ng-model="name"></p>
<ul>
<li ng-repeat="x in names | filter:name | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>
</div>

</div>
<script src="angular.min.js"></script>
<script type="application/javascript">
var myApp=angular.module('myApp',[]);
myApp.controller('uppercaseController',function($scope){
$scope.person = {
firstName: "John",
lastName: "Doe"
};
});
myApp.controller('lowercaseController',function($scope){
$scope.person = {
firstName: "John",
lastName: "Doe"
};
});
myApp.controller('costController',function($scope){
$scope.quantity = 1;
$scope.price = 9.99;
});
myApp.controller('namesController',function($scope){
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}
];
});
myApp.controller('namesFilterController',function($scope){
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}
];
});

</script>
</body>
</html>
显示效果:

AngularJs基础——过滤器