angular--filter的使用

左凯定
2023-12-01

一、在模板中使用
1.内置方法

/*currency:格式化数字为货币格式,默认为‘$’,保留2位小数*/
//用法
{{ num | currency}}
{{ num | currency:'¥',1}}
/*number:数字格式化,默认为添加千位符号(1,000)*/
{{ num | number}}
{{ num | number:2}}  //保留2位小数
/*date:日期格式化,默认格式mediumDate(Sep 25,2019)*/
{{ num | date}}
{{ num | date:'yyyy-MM-dd HH:mm:ss'}}  //一般用法,date有很多内置格式

如想详细了解,请前往https://blog.csdn.net/u013185395/article/details/80449858

/*filter:查找给定数据中拥有当前值的数据*/
{{  [{"age": 20,"id": 20,"name": "iphone"},
        {"age": 22,"id": 21,"name": "sunm xing"},
        {"age": 44,"id": 22,"name": "test abc"}]
         | filter:'1'}}
         //输出 {"age": 22,"id": 21,"name": "sunm xing"}
         
 {{  [{"age": 20,"id": 20,"name": "a"},
        {"age": 22,"id": 21,"name": "b"},
        {"age": 44,"id": 22,"name": "c"}]
         | filter:{'name':'a'}}}
         //输出 {"age": 20,"id": 20,"name": "a"}
         
//filter也支持根据多值查找         
 {{  [{"age": 20,"id": 20,"name": "a"},
        {"age": 22,"id": 21,"name": "b"},
        {"age": 44,"id": 22,"name": "c"}]
         | filter:{'age':'2','name':'a'}}}
         //输出 {"age": 20,"id": 20,"name": "a"}
/*limitTo:截取*/
{{ str | limitTo:3}}//返回前3个字符
{{ arr | limitTo:-1}}//返回数组最后一个元素
/*orderBy:排序(默认为升序,加参数true则为降序)*/
{{ [{"age": 20},{"age": 12}, {"age": 44}] 
        | orderBy:'id':true }}  
        //输出 [{"age": 44},{"age": 20}, {"age": 12}]
        
{{ [{"age": 20},{"age": 12}, {"age": 44}] 
        | orderBy:'id'}}  
        //输出 [{"age": 12},{"age": 20}, {"age": 44}]
/*使用多个filter*/
{{ num | filterName1 | filterName2}}

2.自定义filter

angular.module('app').filter('myFilter', function () {
    return function (value) {
    	/*处理*/
       return value;
    }
});

二,在controller和service中使用
1.注入

app.controller('myController',['$scope','myFilter',function($scope,myFilter){
    $scope.num = myFilter(123456);  
    //在模板中使用{{num}}就可以直接输出 $123,456.00了
}])

2.需要注入多个filter时,应该使用内置的filter服务,用法如下:

app.controller('myController',['$scope','$filter',function($scope,$filter){
	//$filter(filter名称)(需要过滤的内容,参数1,参数2...)
   	$scope.num = $filter('currency')(123534);//等同于$filter('currency')(123534,'$',2)
    $scope.date= $filter('date')(new Date(), 'yyyy-MM-dd');//将日期格式化
    $scope.data = $filter('orderBy')(data,'id',true);//将data里的数据根据id字段降序排列
}])
 类似资料: