过滤器的作用是格式化数据.
过滤器包含:
currency
date
filter
json
limitTo
lowercase
number
orderby
uppercase
使用方法:
1. 在表达式中添加过滤器
<div ng-app="myApp" ng-controller="personCtrl"> <p>The name is {{ lastName | uppercase }}</p> </div> <script> angular.module('myApp',[]).controller('personCtrl',function($scope) { $scope.firstName = "John",$scope.lastName = "Doe" }); </script>
<div ng-app="myApp" ng-controller="namesCtrl"> <p>Looping with objects:</p> <ul> <li ng-repeat="x in names | orderBy:'name'"> {{ x.name + ',' + x.country }} </li> </ul> </div> <script> angular.module('myApp',[]).controller('namesCtrl',function($scope) { $scope.names = [ {name:'Jani',country:'Norway'},{name:'Carl',country:'Sweden'},{name:'Margareth',country:'England'},{name:'Hege',{name:'Joe',country:'Denmark'},{name:'Gustav',{name:'Birgit',{name:'Mary',{name:'Kai',country:'Norway'} ]; }); </script>
3. 自定义过滤器
使用filter()函数
<div ng-app="myApp" ng-controller="myCtrl"> <p>{{name|myFormat}}</p> </div> <script> var app = angular.module('myApp',[]); app.filter('myFormat',function() { return function(name) { var txt = ""; for (var i = 0; i < name.length; i++) { txt += name[i].toUpperCase(); } return txt; } }); app.controller('myCtrl',function($scope) { $scope.name = "John"; }); </script>