angular中常见过滤器
我们从后台请求的数据 有时候不是我们想要的格式
比如货币数字从后台获取过来就是一堆纯数字
但是货币数字通常是 按照规则用逗号分开并且数字前面有标识当前是哪种货币
过滤器的概念:angularjs为我们提供的处理数据格式的方式
过滤器的作用:将数据格式化我们想要的格式
过滤器的分类:内置过滤器 自定义过滤器
使用过滤器的语法:
{{ 数据模型 | 过滤器的名字:过滤器的参数:多个参数以冒号隔开 }}
内置过滤器介绍
currency 货币过滤器
date 日期过滤器
filter 过滤数据
模糊匹配:angularjs会去每一条数据中的每一个字段中去查找 有没有包含过滤条件的数据
精确匹配:angularjs会去每一条数据中的指定字段中去查找 有没有包含过滤条件的数据
limitTo 限制
第一个参数:limit 限制的数量,可以为负数,从后往前开始限制
第二个参数:begin 从第几个开始限制
orderBy 排序
orderBy:'字段' 默认是升序
orderBy:'-字段' 降序
number 数字过滤器
uppercase 大写字符过滤器
lowercase 小写字符过滤器
json 转化为json字符串
代码分析:
{{ money | currency:"¥" }}
{{ time | date:"yyyy-mm-dd hh-mm-ss"}}
- {{item.name}} {{item.age}}
- {{item.name}} {{item.age}}
{{word | limitTo:2:2 }}
{{word | limitTo:-2 }}
- {{item.age}} {{item.name}}
- {{item.age}} {{item.name}}
{{ num | number:2}}
{{ str | uppercase}}
{{ str | lowercase}}
{{persons|json}}angular.module('myApp',[])
.controller('demoCtrl',['$scope',function($scope){
$scope.money = 998;
$scope.time = new Date();
$scope.persons = [
{
name:'1孙悟空2',
age : 500
},
{
name:'1猪八戒2',
age:250
},
{
name:'沙僧',
age:300
},
{
name:'唐僧',
age:100
}
];
$scope.word = "我是好人";
$scope.num = 1234567890987654;
$scope.str = "angular";
}])
angular自定义过滤器
angularjs自身只是提供了一些常用的过滤器,在实际项目中,我们往往会遇到一些比较具体的需求,比如电话号码中间加*、单词首字母大写等等比较个性化的数据格式需求
语法:
如何定义自定义过滤器
模块对象.filter('自定义过滤器名字',[function(){
return function(要处理的数据,滤过器参数1,滤过器参数2,...){
// 具体处理数据的代码
return 处理后的数据;
}
}])
通过例子演示自定义过滤器的使用(首字母大写、电话号码加*)
代码分析:
{{tel | telstar}}
{{Word | firstLetter:'a':'b'}}
angular.module("myApp",[])
.filter("telstar",function(){
//value接受表单中的值
return function(value){
//先截取前三个字符、替换中间的四个字符、拼接后面四个字符
return value.substr(0,3)+"****"+value.substr(7);
}
})
.filter("firstLetter",function(){
return function(value){
//取第一个字符转大写
return value.substr(0,1).toUpperCase()+value.substr(1);
}
})
.controller("demoCtrl",["$scope",function($scope){
$scope.tel="18010972573";
$scope.Word="angular";
}])
本文详细介绍了AngularJS中的过滤器概念及其作用,包括内置过滤器如currency、date、filter、limitTo和orderBy等的使用。同时,讲解了如何自定义过滤器以满足特定的数据格式需求,例如电话号码中间加*和单词首字母大写。并通过实例代码展示了如何在AngularJS应用中实现这些功能。
314

被折叠的 条评论
为什么被折叠?



