0

Filter trong AngularJs

  1. Filter là gì? Filter là 1 trong các component quan trọng của Angularjs. Filter giúp chuyển đổi dữ liệu trước khi dữ liệu đó được các Directive xử lý và được hiển thị trên view. Vì vậy Filter giúp có thể hiển thị nhiều cách khác nhau trên cùng 1 kiểu dữ liệu.
  2. Cú pháp: Có 2 cách làm việc với filter:
  • Cú pháp sử dụng trong Dom: {{ expresstion | filter }}
  • Dùng với service và controller
angular.module('FilterInControllerModule', [])
.controller('FilterController', ['$filter', function($filter) {
  $scope.filteredArray = $filter('filter')(array, argument1, argument2, ...);
}]);
  1. Ưu nhược điểm filter: Filter giúp người dùng giảm số lượng hàm viết trong application, kết hợp với cú pháp ngắn gọn, dễ nhớ. Tuy nhiên filter khi sử xdungj trên view sẽ khiễn cho tốc độ load page bị giảm dẫn đến app bị chậm đi
  2. Một số Filter có sẵn trong AngularJs: currency: định dạng số sang định dạng tiền tệ, filter chọn currency symbol là mặc định, nếu không có tham số gì kèm theo. number: chuyển đổi thành chuỗi số, tách bằng dấu phẩy, numberFilter cũng tùy chọn kích thước số thập phân là bao nhiêu chữ số sau dấu phẩy. lowercase: chuyển đổi thành chuỗi thường. uppercase: chuyển đổi thành chuối hoa. json: đối tượng JSON hoặc array. date: đối tượng ngày, định dạng gồm short, medium, long. limitTo: trả lại kết quả là 1 substring có thể bắt đầu hoặc kết thúc 1 chuỗi. orderBy: lọc trên mảng và sắp xếp. filter: lọc 1 mảng theo: String: nếu có biểu thức chuỗi, AngularJS sẽ tìm từ khóa trong từng đối tượng của mảng và nếu tìm thấy, phần tử sẽ được gọi. (có thể tìm phủ định bằng ! và từ khóa kèm theo). Object: trả về từng phần tử trong mảng. Function: linh động cho nhiều lựa chọn, việc filter có thể tùy ý người lập trình.

VD:

#html
<body  ng-app = "myApp">
    <div ng-controller =" FilterCtrl as ctrl" >
        <div> Amount as a number: {{ctrl.amount | number }}</div>
        <div>Amount as a number: {{ctrl.amount | number:4 }}</div>
        <div>Total Cost as a currency: {{ctrl.totalCost | currency}}</div>
        <div>Total Cost in Euro: {{ctrl.totalCost | currency: "&euro;" }}</div>
        <div>Name: {{ctrl.name | uppercase }}</div>
        <div> Name: {{ctrl.name | lowercase}}</div>
        <div>Name: {{ctrl.name | lowercase| limitTo:7}}</div>
        <div>JSON filter: {{ctrl.obj | json }}</div>
        <div>Start time: {{ctrl.startTime | date}}</div>
        <div>Start time: {{ctrl.startTime | date:'short' }}</div>
        <div>Start time: {{ctrl.startTime | date:'medium' }}</div>
    </div>
 </body>
#angularjs
var myApp = angular.module ('myApp',[])

myApp.controller('FilterCtrl',[function (){
   this.amount = 1000;
   this.totalCost = 2000;
   this.name = 'Do Tuan Minh';
   this.startTime = new Date().getTime();
   this.obj = {name: 'Minh', age:22};
}]);

kết quả khi filter là :

Amount as a number: 1,000 Amount as a number: 1,000.0000 Total Cost as a currency: $2,000.00 Total Cost in Euro: €2,000.00 Name: DO TUAN MINH Name: do tuan minh Name: do tuan JSON filter: { "name": "Minh", "age": 22 } Start time: Mar 25, 2017 Start time: 3/25/17 4:57 PM Start time: Mar 25, 2017 4:57:42 PM

  1. Filter với string, object, function
#html
<body ng-app="myApp"ng-controller="myCtrl">
  <div>
    <h3> Filter by String </h3>
    <form>
      <input ng-model="stringname" type=" text" placeholder="filter by name">
    </form>
    <ul ng-repeat="friend in friends | filter: stringname | orderBy: 'name'">
      <li>{{friend.name}} {{friend.age}}</li>
    </ul>
  </div>

  <div>
    <h3>Filter by Object</h3>
    <form>
      <input type=" text" ng-model="query" placeholder="filter by name and age = 22">
    </form>
    <ul ng-repeat=" friend in friends| filter:{name:query, age:'22'}| orderBy:'name'">
      <li>{{friend.name}} {{friend.age}}</li>
    </ul>
  </div>
  
   <div>
      <h3>Custom Filter</h3>
      <ul ng-repeat="friend in friends | filter: filterFunction | orderBy: 'age' ">
        <li>{{friend.name}} ({{friend.age}})</li>
      </ul>
   </div>
</body>
#angular
var app = angular.module("myApp",[]);
app.controller("MyCtrl", function($scope){
    $scope.friends = [
        {name: "Linh", age: 20},
        {name: "Minh", age: 22},
        {name: "Khanh", age: 43},
        {name: "Dam", age: 12},
        {name: "Son", age: 23},
        {name: "Huan", age: 22},
        {name: "Bich", age: 22},
        {name: "Thanh", age: 22},
        {name: "Gam", age: 22},
        {name: "Chuyen", age: 22},
    ];
   $scope.filterFunction = function(element) {
    return element.name.match(/^Minh/) ? true : false;
  };
});

Kết quả ví dụ: https://plnkr.co/edit/5JSNahyCpmSU52HCU6NL?p=preview Ở trên mình fitler theo string - object và function. Ở đây thấy rõ mình dùng : ng-repeat=" friend in friends| filter:{name:query, age:'22'}| orderBy:'name'" trong đó filter: có tác dụng khi giá trị input thay đổi thì kết quả hiển thị sẽ thay đổi giống với input nhập. orderBy: thì sẽ sắp xếp thứ tự danh sách theo name

  1. Filter với Controller, Service Angularjs cung cấp cho ta các component mà ta có thể sử dụng chúng chỉ cần injected vào service hoặc controller: VD như filterFilter: lọc theo điều kiện, currentcyFilter: lọc theo %, numberFilter: lọc theo số.... VD:
#html
<body ng-app="myApp" ng-controller="myCtrl as ctrl">
    <div>
      All Friend:
      <br>
      <span ng-repeat="friend in ctrl.friends">{{friend.name}}<br> </span><br>
      Filter name is:
      <input ng-model="ctrl.name">
      <span ng-repeat="friend in ctrl.filterFriends">{{friend.name}} </span>
    </div>
  </body>
    #angular
angular.module('myApp', []).
controller('myCtrl', ['filterFilter', '$scope', function(filterFilter, $scope) {
  var _this = this
  _this.friends = [
    {name: "Linh", age: 20},
    {name: "Minh", age: 22},
    {name: "Khanh", age: 43},
    {name: "Dam", age: 12},
    {name: "Son", age: 23},
    {name: "Huan", age: 22},
    {name: "Bich", age: 22},
    {name: "Thanh", age: 22},
    {name: "Gam", age: 22},
    {name: "Chuyen", age: 22},
  ];
  
  $scope.$watch('ctrl.name', function(name){
    return _this.filterFriends = filterFilter(_this.friends, name);
  })
}]);

note: mình dùng $watch ở đây để khi model ctrl.name thay đổi thì sẽ chạy lại hàm filterFilter kết quả các bạn có thể tham khảo ở đây https://plnkr.co/edit/8yCCYhX2iBdLMAvxlXsR?p=preview

  1. Custom Filter Angular cho phép người dùng tự tạo các filter theo từng mục đích khác nhau. Cấu trúc:
app.filter('', function () {
  return function () {
    return;
  };
});

VD:

#html
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <p>{{ username | upperCase }}</p>
      <p>{{ company }}</p>
    </div>
  </body>
#angularjs
var app = angular.module('myApp', []);

app.filter('upperCase', function(){
  return function(item){
    return item.toUpperCase();
  }
});


app.controller('myCtrl', function ($scope, upperCaseFilter) {
    $scope.username = 'Do Tuan Minh';
    $scope.company = upperCaseFilter('Framgia VN')
});

Các bạn có thể xem tại đây: https://plnkr.co/edit/wVM8oZD5VmkPMvfhZ9fQ?p=preview

Ở đây mình trình bầy 2 cách để sử dụng custom filter. Dùng ở Dom và dùng trong service. 7. Kết luận: Mình đã trình bày xong filter trong angularjs. Ưu và nhược điểm của filter trong angularjs. 8. Tài liệu tham khảo: https://docs.angularjs.org/api/ng/filter/filter


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí