>  기사  >  웹 프론트엔드  >  AngularJS 사용자 정의 필터 사용법을 사용하는 방법

AngularJS 사용자 정의 필터 사용법을 사용하는 방법

php中世界最好的语言
php中世界最好的语言원래의
2018-05-29 10:37:191400검색

이번에는 AngularJS 커스텀 필터 사용법과 AngularJS 커스텀 필터 사용 시 주의사항에 대해 알려드리겠습니다. 실제 사례를 살펴보겠습니다.

필터 구조

{{带过滤数据 | 过滤器名:参数1:参数2:参数3.....}}
app.filter('过滤器名', function () {
    return function (待过滤数据, 参数....) {
           ......
      return 已过滤数据;
 }

예 1:

<!doctype html>
<html ng-app="myApp">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body>
<p ng-controller="myAppCtrl">
  <p>
    <table>
      <tr>
        <th>Name</th>
        <th>Phone</th>
      </tr>
      <!--写法1-->
      <tr ng-repeat="friend in friends |myfilter">
      <!--写法2-->
<!--<tr ng-repeat="friend in newArr=(friends | myfilter)">-->
        <td>{{friend.name}}</td>
        <td>{{friend.phone}}</td>
      </tr>
    </table>
  </p>
</p>
<script type="text/javascript">
  var app = angular.module("myApp", []);
  app.controller("myAppCtrl", ["$scope", function ($scope) {
    $scope.friends = [{name: 'John', phone: '44555-1276'},
      {name: 'Annie', phone: '800-BIG-MARY'},
      {name: 'Mike', phone: '11555-4321'},
      {name: 'Adam', phone: '33555-5678'},
      {name: 'David', phone: '387555-8765'},
      {name: 'Mikay', phone: '555-5678'}];
  }]);
  app.filter("myfilter", function () {
    return function (input) {
      var output = [];
      angular.forEach(input, function (value, key) {
        console.log("value==" + JSON.stringify(value));
        console.log("value.phone类型==" + typeof (value.phone));
        console.log("value.phone.indexOf==" + value.phone.indexOf("555"));
        /*js中没有contains方法,使用indexOf来判断字符串是否包含*/
        /*indexOf字符串出现的位置,没有则返回-1*/
        //方法一:
        if (value.phone.indexOf("555") >= 0) {
          output.push(value);
        }
        //方法二:
//        if (value.phone.indexOf("555") !== -1) {
//          output.push(value);
//        }
      });
      return output;
    }
  });
</script>
</body>
</html>

포함 여부 4: 필터

<!doctype html>
<html ng-app="myApp">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body>
<p ng-controller="myAppCtrl">
  姓名:{{ name }}<br>
  倒序:{{ name | reverse }}<br>
  倒序并大写:{{ name | reverse:true }}
</p>
<script type="text/javascript">
  var myAppModule = angular.module("myApp", []);
  myAppModule.controller("myAppCtrl", ["$scope", function ($scope) {
    $scope.name = "xuqiang";
  }]);
  myAppModule.filter("reverse", function () {
    return function (input, uppercase) {
      <!--input就是其中name代表的值。-->
      <!--uppercase这个bool值,判断是否要进行大小写转换。-->
      var out = "";
      for (var i = 0; i < input.length; i++) {
        out = input.charAt(i) + out;
      }
      if (uppercase) {
        out = out.toUpperCase();
      }
      return out;
      <!--返回过滤后的字符串-->
    }
  });
</script>
</body>
</html>

예 5 : 정렬

<!doctype html>
<html ng-app="myApp">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body ng-controller="myAppCtrl">
<p>
  <p>
    {{welcome | replaceHello}}<br/>
    {{welcome | replaceHello:3:5}}<br/>
  </p>
</p>
<script type="text/javascript">
  var app = angular.module("myApp", []);
  app.controller("myAppCtrl", ["$scope", function ($scope) {
    $scope.welcome = "Hello AngularJs";
  }]);
  //自定义过滤器
  app.filter('replaceHello', function () {
    return function (input, n1, n2) {
      console.log("input==" + input);
      console.log("n1==" + n1);
      console.log("n2==" + n2);
      return input.replace(/Hello/, '您好');
    }
  });
</script>
</body>
</html>

예 6: 입력 필터링

<!doctype html>
<html ng-app="a3_3">
<head>
  <title>自定义过滤器</title>
  <script src="../Script/angular.min.js"
      type="text/javascript"></script>
  <style type="text/css">
    body {
      font-size: 12px;
    }
    ul {
      list-style-type: none;
      width: 408px;
      margin: 0px;
      padding: 0px;
    }
    ul li {
      float: left;
      padding: 5px 0px;
    }
    ul .odd {
      color: #0026ff;
    }
    ul .even {
      color: #ff0000;
    }
    ul .bold {
      font-weight: bold;
    }
    ul li span {
      width: 52px;
      float: left;
      padding: 0px 10px;
    }
    ul .focus {
      background-color: #cccccc;
    }
  </style>
</head>
<body>
<p ng-controller="c3_3">
  <ul>
    <li ng-class="{{bold}}">
      <span>序号</span>
      <span>姓名</span>
      <span>性别</span>
      <span>年龄</span>
      <span>分数</span>
    </li>
    <li ng-repeat=" stu in data | young:0"
      ng-class-odd="&#39;odd&#39;"
      ng-class-even="&#39;even&#39;">
      <span>{{$index+1}}</span>
      <span>{{stu.name}}</span>
      <span>{{stu.sex}}</span>
      <span>{{stu.age}}</span>
      <span>{{stu.score}}</span>
    </li>
  </ul>
</p>
<script type="text/javascript">
  var a3_3 = angular.module('a3_3', []);
  a3_3.controller('c3_3', ['$scope', function ($scope) {
    $scope.bold = "bold";
    $scope.data = [
      {name: "张明明", sex: "女", age: 24, score: 95},
      {name: "李清思", sex: "女", age: 27, score: 87},
      {name: "刘小华", sex: "男", age: 28, score: 86},
      {name: "陈忠忠", sex: "男", age: 23, score: 97}
    ];
  }]);
  a3_3.filter('young', function () {
    return function (e, type) {
      var _out = [];
      var _sex = type ? "男" : "女";
      for (var i = 0; i < e.length; i++) {
        if (e[i].age > 22 && e[i].age < 28 &&
          e[i].sex == _sex)
          _out.push(e[i]);
      }
      return _out;
    }
  });
</script>
</body>
</html>

이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요! 추천 도서:

Vue에서 문자열 템플릿을 사용하는 방법

bison으로 인한 Mac 설치 중고품 오류 처리 방법

위 내용은 AngularJS 사용자 정의 필터 사용법을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.