AngularJS过滤器
AngularJS过滤器可用于转换数据:
过滤器 描述
lowercase 格式化字符串为小写
uppercase 格式化字符串为大写
currency 格式化数字为货币格式
orderBy 根据某个表达式排列数组
filter 从数组项中选择一个子集
date 日期格式化(date:"yyyy-MM-dd HH:mm:ss")
number 保留小数
limitTo 截取
过滤管道 |
表达式中添加过滤器
uppercase 过滤器将字符串格式化为大写:
{
{sex | uppercase}}
- { {x.name + "," +x.country}}
angular.module("myApp",[]).controller("namesCtrl",function($scope){ $scope.names = [ {name:"Jani",country:"Norway"}, {name:"Hege",country:"Sweden"}, {name:"Kai",country:"Denmark"} ]; $scope.sex = "boy";})
lowercase 过滤器将字符串格式化为小写:
currency 过滤器将数字转化为货币格式:
总价 = {
{(quantity*price) | currency}}{
{sex | uppercase}}
- { {x.name + "," +x.country}}
向指令添加过滤器
过滤器可以通过一个管道字符|和一个过滤器添加到指令中,该过滤器后可以跟一个冒号和一个模型名称
orderBy(根据id升序排列)
总价 = {
{(quantity*price) | currency}}{
{sex | uppercase}}
- { {(x.name | uppercase) + "," +x.country + "," + x.id}}
angular.module("myApp",[]).controller("namesCtrl",function($scope){ $scope.names = [ {name:"Jani",country:"Norway",id:"3"}, {name:"Hege",country:"Sweden",id:"1"}, {name:"Kai",country:"Denmark",id:"2"} ]; $scope.sex = "boy"; $scope.price = "23.0"; $scope.quantity = "6";})
orderBy(根据id倒序排列)
总价 = {
{(quantity*price) | currency}}总价 = {
{(quantity*price) | currency:"RMB ¥"}}{
{sex | uppercase}}
- { {(x.name | uppercase) + "," +x.country + "," + x.id}}
{
{msg | reverse}}
自定义过滤器
以下实例自定义一个过滤器reverse,将字符串反转:
总价 = {
{(quantity*price) | currency}}总价 = {
{(quantity*price) | currency:"RMB ¥"}}{
{sex | uppercase}}
- { {(x.name | uppercase) + "," +x.country + "," + x.id}}
{
{msg | reverse}}
var app = angular.module("myApp",[]);app.controller("namesCtrl",function($scope){ $scope.names = [ {name:"Jani",country:"Norway",id:"3"}, {name:"Hege",country:"Sweden",id:"1"}, {name:"Kai",country:"Denmark",id:"2"} ]; $scope.sex = "boy"; $scope.price = "23.0"; $scope.quantity = "6"; $scope.msg = "酷我音乐调频";})// 自定义过滤器reverseapp.filter("reverse",function(){ //可以注入依赖 return function (text){ return text.split("").reverse().join(""); }})
date格式化
{ {1490161945000 | date:"yyyy-MM-dd HH:mm:ss"}}
<!--2017-03-22 13:52:25-->
number格式化(保留小数)
{ {1490161945000 | date:"yyyy-MM-dd HH:mm:ss"}} { {149016.1945000 | number:2}}
filter查找
从数组项中选择一个子集(查找id:3的行)
{ { names | filter:{'id':'3'} }}
var app = angular.module("myApp",[]); app.controller("namesCtrl",function($scope){ $scope.names = [ {name:"Jani",country:"Norway",id:"3"}, {name:"Hege",country:"Sweden",id:"1"}, {name:"Kai",country:"Denmark",id:"2"} ]; $scope.sex = "boy"; $scope.price = "23.0"; $scope.quantity = "6"; $scope.msg = "酷我音乐调频"; })
limitTo截取
{ {"1234567890" | limitTo :6}} { {"1234567890" | limitTo :-6}}