在HTML中使用
{{ name | uppercase }} <!--将字符串转成大写-->
在JS中使用
- 需要引入$filter
app.controller('DemoController', ['$scope', '$filter',
function($scope, $filter) {
$scope.name = $filter('lowercase')('Ari'); //调用转小写的过滤器:lowercase来处理字符串:Ari
}]);
给过滤器传值
<!-- 显示:123.46 -->
{{ 123.456789 | number:2 }}
可以用 | 符号作为分割符来同时使用多个过滤器
自定义过滤器
example:
angular.module('myApp.filters', [])
.filter('capitalize', function() {
return function(input) {
// input是我们传入的字符串
if (input) {
return input[0].toUpperCase() + input.slice(1);
}
});
<!-- Ginger loves dog treats -->
{{ 'ginger loves dog treats' | lowercase | capitalize }}
常用过滤器
-
currency
-
将一个数值格式化为货币格式
{{ 123 | currency }}
date
-
将日期格式化成需要的格式
{{ today | date:'medium' }} <!-- Aug 09, 2013 12:09:02 PM --> {{ today | date:'short' }} <!-- 8/9/1312:09PM --> {{ today | date:'fullDate' }} <!-- Thursday, August 09, 2013 --> {{ today | date:'longDate' }} <!-- August 09, 2013 --> {{ today | date:'mediumDate' }}<!-- Aug 09, 2013 --> {{ today | date:'shortDate' }} <!-- 8/9/13 --> {{ today | date:'mediumTime' }}<!-- 12:09:02 PM --> {{ today | date:'shortTime' }} <!-- 12:09 PM -->
filter
-
从给定数组中选择一个子集,并将其生成一个新数组返回
{{ ['Ari','Lerner','Likes','To','Eat','Pizza'] | filter:'e' }} <!-- ["Lerner","Likes","Eat"] -->
json
-
将一个JSON或JavaScript对象转换成字符串
{{ {'name': 'Ari', 'City': 'SanFrancisco'} | json }} <!-- { "name": "Ari", "City": "San Francisco" } -->
limitTo
-
根据传入的参数生成一个新的数组或字符串,新的数组或字符串的长度取
决于传入的参数,通过传入参数的正负值来控制从前面还是从后面开始截取<!--截取前三个字符--> {{ San Francisco is very cloudy | limitTo:3 }} <!-- San --> <!--截取后六个字符--> {{ San Francisco is very cloudy | limitTo:-6 }} <!-- cloudy --> {{ ['a','b','c','d','e','f'] | limitTo:1 }} <!-- ["a"] -->
lowercase
-
转小写
{{ "San Francisco is very cloudy" | lowercase }} <!-- san francisco is very cloudy -->
uppercase
-
转大写
{{ "San Francisco is very cloudy" | uppercase }} <!-- SAN FRANCISCO IS VERY CLOUDY -->
number
-
将数字格式化成文本。它的第二个参数是可选的,用来控制小数点后截取的位数,如果传入了一个非数字字符,会返会空字符串。
{{ 123456789 | number }} <!-- 1,234,567,890 -->
orderBy
-
可以用表达式对指定的数组进行排序
{{ [{ 'name': 'Ari', 'status': 'awake' },{ 'name': 'Q', 'status': 'sleeping' },{ 'name': 'Nate', 'status': 'awake' }] | orderBy:'name' }} <!-- 输出 [ {"name":"Ari","status":"awake"}, {"name":"Nate","status":"awake"}, {"name":"Q","status":"sleeping"} ] --> <!-- orderBy:'name':true 对排序结果进行反转 -->