<!DOCTYPE html> <!--指定angular管理的范围--> <html ng-app="app01"> <head> <meta charset="UTF-8"> <title>过滤器</title> </head> <body> <!--指定控制器的作用范围--> <form ng-controller="Controller1"> <p> 货币:{{money}} ,{{money|currency}} ,{{money|currency:"¥"}} </p> <p> 数字:{{money|number:1}} ,{{money | number:1 | currency:"$" }} </p> <p> 大写:{{message|uppercase}} </p> <p> 小写:{{message|lowercase}} </p> <p> json:{{user | json}} </p> <p> 截取:{{message|limitTo:5|uppercase}} </p> <p> 日期1:{{birthday|date:'yyyy年MM月dd日 HH:mm:ss'}} </p> <p> 日期2:{{birthday|date:'fullDate'}} </p> <p> 排序:{{users|orderBy:'age':true}} </p> </form> <!--引入angularjs框架--> <script src="https://www.jb51.net/js/angular146/angular.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> //定义模块,指定依赖项为空 var app01 = angular.module("app01", []); //定义控制器,指定控制器的名称,$scope是全局对象 app01.controller("Controller1", function($scope) { $scope.money=1985.678; $scope.message="Hello AngularJS!" $scope.user={name:"rose",age:18}; $scope.birthday=new Date(); $scope.users=[{name:"rose",age:18},{name:"jack",age:19},{name:"tome",age:17}]; }); </script> </body> </html>
运行结果:
2.1.2、在脚本中调用过滤函数
在函数中调用过滤器的方法是:在控制中添加对的依赖,filter的依赖,filter("过滤函数名称")(被过滤对象,'参数')
示例代码:
<!DOCTYPE html> <!--指定angular管理的范围--> <html ng-app="app01"> <head> <meta charset="UTF-8"> <title>过滤器</title> </head> <body> <!--指定控制器的作用范围--> <form ng-controller="Controller1"> {{money}} <hr/> {{moneyString}} </form> <!--引入angularjs框架--> <script src="https://www.jb51.net/js/angular146/angular.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> //定义模块,指定依赖项为空 var app01 = angular.module("app01", []); //定义控制器,指定控制器的名称,$scope是全局对象 app01.controller("Controller1", function($scope,$filter) { $scope.money=1985.897; //使用$filter服务查找currency函数,并调用 $scope.moneyString=$filter("currency")($scope.money,'USD$'); }); </script> </body> </html>
运行结果:
2.2、自定义过滤器
示例代码:
<!DOCTYPE html> <!--指定angular管理的范围--> <html ng-app="app01"> <head> <meta charset="UTF-8"> <title>过滤器</title> </head> <body> <!--指定控制器的作用范围--> <form ng-controller="Controller1"> <p> {{"Hello AngularJS and NodeJS" | cutString:15:'...'}} </p> <p> {{longString}} </p> </form> <!--引入angularjs框架--> <script src="https://www.jb51.net/js/angular146/angular.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> //定义模块,指定依赖项为空 var app01 = angular.module("app01", []); //向模块中添加过滤 //用于裁剪字符,超过长度则截取,添加... app01.filter("cutString",function(){ return function(srcString,length,addString){ if(srcString.length<length){ return srcString; } return srcString.substring(0,length)+addString; } }); //定义控制器,指定控制器的名称,$scope是全局对象 app01.controller("Controller1", function($scope,$filter) { $scope.longString=$filter("cutString")("Hello AngularJS and NodeJS",5,":):):)"); }); </script> </body> </html>
运行结果:
练习1: