1.过滤器可以使用一个管道字符(|)添加到表达式和指令中。
再次强调一点,所有的运行都要加入angularJS的库文件(类似JQuery的引用)
常见的AngularJS 过滤器
(1) lowercase和uppercase过滤器(大小写)
<div ng-app="myApp" ng-controller="myCtrl"> <p>名字: {{userName|uppercase}}</p><!-- 转化为大写 --> <p>姓氏: {{lastname|lowercase}}</p><!-- 转化为小写 --> </div> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller('myCtrl',function($scope){ $scope.userName ="hello yyy"; $scope.lastname = "REEfsnes"; }); </script>
结果如下:
(2)Currency过滤器(美元符号)
<div ng-app="myApp" ng-controller="myCtrl"> <p>单价<input type="number" ng-model="price" /></p> <p>数量<input type="number" ng-model="quantity"/> </p> <h2 >总价为:{{(price*quantity) | currency}}</h2><!-- 表达式 --> </div> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller('myCtrl',function($scope){ $scope.price = 12; $scope.quantity = 2; }); </script>
结果如下:
(3)orderBy过滤器(排序数组)
<div ng-app="myApp" ng-controller="myCtrl"> <!-- 通过国家排序 --> <p>通过国家排序</p> <ul> <li ng-repeat="x in names | orderBy:'country'"> {{ x.name + ', ' + x.country }} </li> </ul> <!-- 通过名字排序 --> <p>通过名字排序</p> <ul> <li ng-repeat="x in names | orderBy:'name'"> {{ x.name + ', ' + x.country }} </li> </ul> </div> <script type="text/javascript"> var app = angular.module('myApp', []); angular.module('myApp', []).controller('myCtrl', function($scope) { $scope.names = [{ name: 'Jemy', country: 'Norway' }, { name: 'Peter', country: 'Sweden' }, { name: 'Kaisa', country: 'Denmark' }]; }); </script>
结果如下:
(4)filter过滤器(过滤输入)
<div ng-app="myApp" ng-controller="myCtrl"> <p>输入过滤 <input type="text" ng-model="test"/ placeholder="请输入过滤的字符"></p> <!-- 过滤输入后通过名字排序 --> <ul> <li ng-repeat="x in names| filter:test |orderBy:'name'"> {{ (x.name) + ', ' + x.country }} </li> </ul> </div> <script type="text/javascript"> var app = angular.module('myApp', []); angular.module('myApp', []).controller('myCtrl', function($scope) { $scope.names = [{ name: 'Jemy', country: 'Norway' }, { name: 'Peter', country: 'Sweden' }, { name: 'Kaisa', country: 'Denmark' }]; });
输入p后结果如下: