- 不同过滤器的小demo。
currency
number
uppercase
json
limitTo
date
orderBy
filter
<script> var filterMy = angular.module("fliterMy",[]); filterMy. controller("filter", ["$scope",function($scope) $scope.name = "345343"; $scope.str = "hello"; $scope.jsonTest = {"name" : "Gary" , "age" , 10};
$scope.numbers = [
{"color":"red","age":"20"},
{"color":"yellow","age":"30"},
{"color":"blue","age":"40"},
{"color":"green","age":"50"}
]
]) </script> <body> <div ng-controller = "filter"> <p>{{name | curency:"¥"}}</p> //¥345,343.00 <p>{{name | number}}</p> //345,343当有小数时候,默认保留3位,number:2保留两位小数; <p>{{str | uppercase}}</p> //HELLO <pre>{{jsonTest | json}}</pre> //将json格式化成标准格式 <p>{{str | limitTo : 3}}</p> // hel 同时,limitTo 也可以支持数组的截取
<p>{{name | date}}</p> //将毫秒数输出日期格式,参数可以有很多,输出不同的日期格式
<p>{{numbers | orderBy : 'color' :true}}</p> //按照color排序,true代表是降序
<p>{{numbers | filter : '40'}}</p> //匹配数组中存在40所在项,filters :'l':true 完全匹配
</div> </body>
- 过滤器扩展-组合使用
过滤器可以组合使用,通过多个 | 符号,比如:
<p>{{str | limitTo : 3 | uppercase}}</p> //取前3位,并且变成大写
- js中使用过滤器$filter
<script> var filterMy = angular.module("fliterMy",[]); filterMy. controller("filter", ["$scope","$fliter",function($scope,$filter) $scope.name = $filter('number')('345343'); ]) </script> <body> <div ng-controller = "filter"> <p>{{name}}</p> //¥345,343.00 </div> </body>
- 自定义过滤器
<script> var filterMy = angular.module("fliterMy",[]); filterMy.filter('firstUpper',function(){ return function(str){ return str.charAt(0).toUppercase() +str.substring(1); } }) filterMy.controller("filter", ["$scope",function($scope) $scope.str = "hello"; ]) </script>
<body> <div ng-controller = "filter"> <p>{{name | firstUpper}}</p> </div> </body>
- js中使用自定义过滤器
<script> var filterMy = angular.module("fliterMy",[]); filterMy.filter('firstUpper',function(){ return function(str){ return str.charAt(0).toUppercase() +str.substring(1); } }) filterMy.controller("filter",["$scope","$filter",function($scope,$filter) $scope.name = $filter('firstUpper')('hello');//js中使用过滤器 ]) </script> <body> <div ng-controller = "filter"> <p>{{name}}</p> </div> </body>