AngularJS 过滤器
AngularJS 过滤器,AngularJS中添加了一些过滤器,以便更轻松地格式化和处理数据。AngularJS中有几个内置过滤器。这里列出了它们以及一些示例,以便更容易理解。
基本语法:
例如,过滤器{{ fullName | uppercase }}将 fullName 格式化为大写格式。
AngularJS 中的一些常用过滤器是:
- currency数字被格式化为货币格式。
- date将日期指定为特定格式。
- filter根据提供的条件过滤数组。
- limitTo数组或字符串被限制为指定数量的元素/字符。
- number如果格式化为字符串,则为数字。
- orderBy数组按表达式排序。
- lowercase此过滤器将字符串转换为小写字母。
- uppercase 此过滤器将字符串转换为大写字母。
- json它将 JavaScript 对象转换为 JSON 字符串。
- currency过滤器:
此过滤器只是将数字格式化为货币。<!DOCTYPE html> <html> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body> <div ng-app="myApp" ng-controller="costCtrl"> <h1>Currency Format - GeeksforGeeks</h1> <h2>Price: {{ price | currency }}</h2> </div> <script> var app = angular.module('myApp', []); app.controller('costCtrl', function($scope) { $scope.price = 20; }); </script> </body> </html>
输出:
- date 过滤器:
date 过滤器将日期格式化为指定格式。语法:{{ date | date : format : timezone }}
<!DOCTYPE html> <html> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body> <div ng-app="myApp" ng-controller="datCtrl"> <h1>GeeksforGeeks - Date Filter</h1> <p>Date = {{ today | date }}</p> </div> <script> var app = angular.module('myApp', []); app.controller('datCtrl', function($scope) { $scope.today = new Date(); }); </script> </body> </html>
输出:
- Filter:
用于仅显示所需的对象。筛选器选择数组的子集。
例如,此筛选器只能用于数组,因为它返回仅包含匹配项的数组(数组中给定的条件)。<!DOCTYPE html> <html> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body> <div ng-app="myApp" ng-controller="namesCtrl"> <h1>filter - GeeksforGeeks</h1> <ul> <li ng-repeat="x in names | filter : 'e'"> {{ x }} </li> </ul> </div> <script> angular.module('myApp', []).controller('namesCtrl', function($scope) { $scope.names = [ 'Jani', 'Carl', 'Margareth', 'Hege', 'Joe', 'Gustav', 'Birgit', 'Mary', 'Kai' ]; }); </script> <p>This example displays only the names containing the letter "e".</p> </body> </html>
输出:
- limitTo 过滤器:
此过滤器返回一个包含指定数量元素的数组或字符串。输出将取决于提供给程序的输入类型。当用于数组时,它返回一个包含指定数量的数组。
在字符串的情况下,它返回一个只包含指定数量的字符的字符串,而当用于数字时,它返回一个只包含指定位数的字符串。语法:{{ object | limitTo : limit : begin }}
在这里,limit 指定要显示的元素数量, begin 指定从哪里开始限制。
<!DOCTYPE html> <html> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body> <div ng-app="myApp" ng-controller="jsCtrl"> <h1>GeeksforGeeks</h1> <pre>{{customer | json : 20}}</pre> </div> <script> var app = angular.module('myApp', []); app.controller('jsCtrl', function($scope) { $scope.customer = { "name" : "Milk", "city" : "Patna", "country" : "India" }; }); </script> <p>A JSON string with 20 spaces per indentation.</p> </body> </html>
输出:
让我们看一下数组过滤器的示例。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!