AngularJS过滤器
过滤器可以使用一个管道字符(|)添加到表达式和指令中。
uppercase(变为大写):
<div ng-app="myApp" ng-controller="personCtrl">
<p>姓名为 {{ lastName | uppercase }}</p>
</div>
<p>姓名为 {{ lastName | uppercase }}</p>
</div>
lowercase(变为大写):
<div ng-app="myApp" ng-controller="personCtrl">
<p>姓名为 {{ lastName | lowercase }}</p>
</div>
<p>姓名为 {{ lastName | lowercase }}</p>
</div>
currency 过滤器将数字格式化为货币格式:
1 <div ng-app="myApp" ng-controller="costCtrl"> 2 3 数量: <input type="number" ng-model="quantity"> 4 价格: <input type="number" ng-model="price"> 5 6 <p>总价 = {{ (quantity * price) | currency }}</p> 7 8 </div> 9 10 <script> 11 var app = angular.module('myApp', []); 12 app.controller('costCtrl', function($scope) { 13 $scope.quantity = 1; 14 $scope.price = 9.99; 15 }); 16 </script>
orderby(排序):
1 <div ng-app="myApp" ng-controller="namesCtrl"> 2 3 <p>循环对象:</p> 4 <ul> 5 <li ng-repeat="x in names | orderBy:'name'"> 6 {{ x.name + ', ' + x.country }} 7 </li> 8 </ul> 9 10 </div> 11 12 <script > 13 var app = angular.module("myApp", []); 14 app.controller('namesCtrl', function($scope){ 15 $scope.names = [ 16 {name:"longjiang1",country:"3"}, 17 {name:"longjiang2",country:"1"}, 18 {name:"longjiang3",country:"2"} 19 ]; 20 }); 21 </script>
过滤输入
输入过滤器可以通过一个管道字符(|)和一个过滤器添加到指令中,该过滤器后跟一个冒号和一个模型名称。
filter 过滤器从数组中选择一个子集:
<div ng-app="myApp" ng-controller="namesCtrl"> <p>输入过滤:</p> <p><input type="text" ng-model="test"></p> <ul> <li ng-repeat="x in names | filter:test | orderBy:'country'"> {{ (x.name | uppercase) + ', ' + x.country }} </li> </ul> </div> <script> angular.module('myApp', []).controller('namesCtrl', function($scope) { $scope.names = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sweden'}, {name:'Kai',country:'Denmark'} ]; }); </script>