首页  >  文章  >  web前端  >  过滤器与自定义过滤器的介绍

过滤器与自定义过滤器的介绍

一个新手
一个新手原创
2017-10-10 10:17:091862浏览

angularjs中的过滤器为了实现对于表达式结果的筛选、过滤、格式化,达到更好的表现效果。
过滤器的语法:支持多重过滤和传参
{{expression | 过滤器名称 : ‘参数’ | 过滤器名称2:‘参数’ }}
方式:| -》 管道

常用的过滤器:
currency 货币样式的过滤器
date 日期
uppercase/lowercase 大小写的处理
orderBy 对指定的数组进行升序或者降序排列
number 格式化数字为文本(对有小数点的数据的处理)
limitTo 限定数组或者字符串要显示的个数

<!DOCTYPE html><html ng-app="myApp"><head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <script src="js/angular.js"></script></head><body><p ng-controller="myCtrl">
  <table>
    <thead>
      <tr>
        <th>名字</th>
        <th>分数</th>
        <th>年龄</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="stu in stuList | orderBy:&#39;score&#39;:true | limitTo:3">
        <td>{{stu.name}}</td>
        <td>{{stu.score}}</td>
        <td>{{stu.age}}</td>
      </tr>
    </tbody>
  </table></p><script>
  var app = angular.module(&#39;myApp&#39;, [&#39;ng&#39;]);

  app.controller(&#39;myCtrl&#39;, function ($scope) {
    $scope.stuList = [
      {name:&#39;Mary0&#39;,age:20,score:80},
      {name:&#39;Mary1&#39;,age:21,score:70},
      {name:&#39;Mary2&#39;,age:22,score:88},
      {name:&#39;Mary3&#39;,age:23,score:90},
      {name:&#39;Mary4&#39;,age:24,score:60}
    ]
  });</script></body></html>

这里写图片描述

自定义过滤器方式:

app.filter(‘过滤器名称’,function(){
   return function(input,arg){
           //input是传递给过滤器的数据
           //arg 是过滤器本身的参数
       return ‘过滤后的结果’
   }
})

<!DOCTYPE html><html ng-app="myApp"><head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <script src="js/angular.js"></script></head><body><p ng-controller="myCtrl">
  <!-- 将price所对应的值通过管道传递给自定义的过滤器-->
  <h1>{{price | myFilter:&#39;¥&#39; }}</h1></p><script>
  var app = angular.module(&#39;myApp&#39;, [&#39;ng&#39;]);  //创建过滤器:过滤器的本质是方法,有输入有输出
  app.filter(&#39;myFilter&#39;, function () {
    return function (input,arg) {
      console.log(        &#39;输入为&#39;+input+" 过滤器的参数为:"+arg);     
      var output = arg+input;      
      return output;
    }
  })

  app.controller(&#39;myCtrl&#39;, function ($scope) {
      $scope.price = 100;
  });</script></body></html>

以上是过滤器与自定义过滤器的介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn