AngularJS 霸道的过滤器小结(4)

<!DOCTYPE> <!-- use module --> <html ng-app="exampleApp"> <head> <title>Angluar test</title> <meta charset="utf-8"/> <link type="text/css" href="https://www.jb51.net/css/bootstrap.min.css" > <link type="text/css" href="https://www.jb51.net/css/bootstrap-theme.min.css" > </head> <body> <dlv ng-controller="defaultCtrl"> <div> Products <span>{{products.length}}</span> </div> <div> <table> <thead> <tr><th>Name</th><th>Category</th><th>Expiry</th><th>Price</th></tr> </thead> <tbody> <tr ng-repeat="p in products"> <!-- 使用自定义过滤器 --> <td>{{p.name | labelCase}}</td> <td>{{p.category | labelCase : true}}</td> <td>{{p.expiry}}</td> <td>{{p.price | number : 2}}</td> </tr> </tbody> </table> </div> </dlv> <script type="text/javascript" src="https://www.jb51.net/js/angular.min.js"></script> <script type="text/javascript"> var myApp = angular.module("exampleApp", []); myApp.controller("defaultCtrl", function ($scope) { $scope.products = [ { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 }, { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 }, { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }, { name: "Tuna", category: "Fish", price: 20.45, expiry: 3 }, { name: "Trout", category: "Fish", price: 12.93, expiry: 4 }, { name: "Salmon", category: "Fish", price: 17.93, expiry: 2 }, { name: "Beer", category: "Drinks", price: 2.99, expiry: 365 }, { name: "Wine", category: "Drinks", price: 8.99, expiry: 365 }, { name: "Whiskey", category: "Drinks", price: 45.99, expiry: 365 } ]; }); </script> <!-- 引入自定义的过滤器 --> <script type="text/javascript" src="https://www.jb51.net/js/createFilters.js"></script> </body> </html>

自定义过滤器,labelCase反转字符串

// js/createFilters.js文件 angular.module("exampleApp") .filter("labelCase", function () { return function (value, reverse) { if (angular.isString(value)) { var inter = reverse ? value.toUpperCase() : value.toLowerCase(); return (reverse ? inter[0].toLowerCase() : inter[0].toUpperCase()) + inter.substr(1); } else { return value; } } })

这里写图片描述

 

2.创建集合过滤器

在createFilter中定义一个skip过滤函数

angular.module("exampleApp") .filter("labelCase", function () { return function (value, reverse) { if (angular.isString(value)) { var inter = reverse ? value.toUpperCase() : value.toLowerCase(); return (reverse ? inter[0].toLowerCase() : inter[0].toUpperCase()) + inter.substr(1); } else { return value; } } }) .filter("skip", function () { return function (value, count) { if (angular.isArray(value) && angular.isNumber(count)){ if (count > value.length || count < 0) { return value; } else { // 跳过数组前两项 return value.slice(count); } } else { return value; } } })

在视图中使用

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wypgwy.html