AngularJS Filters

Các ví dụ về AngularJS Filters đầy đủ từ a-z

  1. AngularJS cung cấp một số Filters
  2. Ví dụ tạo chữ hoa trong angular
  3. Sắp xếp dữ liệu trong angular
  4. Ví dụ lọc dữ liệu với filter
  5. Lọc theo nhiều điều kiện json
  6. Lọc Angular chính xác theo cột angular
  7. Lọc filter angular dạng copy table
  8. Ví dụ tạo hàm filter nâng cao riêng biệt

AngularJS cung cấp một số Filters


    currency hiển thị định dạng tiền đô
    date định dạng ngày
    filter lọc các phần tử trong biến mảng.
    json định dạng biến object đến a JSON string.
    limitTo
    lowercase chuyển chữ thường.
    number định dạng kiểu số.
    orderBy sắp xếp mảng.
    uppercase chữ hoa.

Ví dụ tạo chữ hoa trong angular
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ Ten | uppercase }}</p>
</div>

Sẽ in Ten thành chữ hoa
 

Sắp xếp dữ liệu trong angular
<!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">
<p>Danh sách nhân viên:</p>
<ul>
  <li ng-repeat="x in NhanVien | orderBy:'Tuoi'">
    {{ x.Ten + ', ' + x.Tuoi }}
  </li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.NhanVien = [
        {Ten:'Jani',Tuoi:30},
        {Ten:'Carl',Tuoi:20},
        {Ten:'Margareth',Tuoi:18},
        {Ten:'Hege',Tuoi:37},
        {Ten:'Joe',Tuoi:20}      
        ];
});
</script>
</body>
</html>

Ví dụ lọc dữ liệu với filter
Cùng như bài trên nhưng đổi lại filter:'30'
<li ng-repeat="x in NhanVien | filter:'30'">
    {{ x.Ten + ', ' + x.Tuoi }}
  </li>

Kết quả ra danh sách nhân viên tuổi 30

* Cũng như ví dụ trên giờ ta thêm 1 input, nhập giá trị tuổi và để lọc ra
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Danh sách nhân viên:</p>
Tuổi tìm: <input type="text" ng-model="TimTuoi">
<ul>
  <li ng-repeat="x in NhanVien | filter : TimTuoi">
    {{ x.Ten + ', ' + x.Tuoi }}
  </li>
</ul>
</div>

 
Lọc theo nhiều điều kiện json
1 điều kiện
<div ng-repeat="product in products | filter: { color: 'red' }">

2 điều kiện trở lên

<div ng-repeat="x in Data_BangGia | filter:MyFilter">
      $scope.MyFilter= function(item) {
             if (item.Ten_HangHoa === 'Giày WEEN' || item.Ten_HangHoa  === 'Mũ đai da') {
              return item;
             }
         };

  * Hàm MyFilter kiểm tra điều kiện nếu đúng thì trả về bảng ghi để hiển thị, nếu sai thì không ra về.

Chú ý: khi các giá trị

  

Lọc Angular chính xác theo cột angular

<div ng-init="friends = [{name:'John', phone:'555-1276'},
                         {name:'Mary', phone:'800-BIG-MARY'},
                         {name:'Mike', phone:'555-4321'},
                         {name:'Adam', phone:'555-5678'},
                         {name:'Julie', phone:'555-8765'},
                         {name:'Juliette', phone:'555-5678'}]"></div>

<label>Search: <input ng-model="searchText"></label>
<table id="searchTextResults">
  <tr><th>Name</th><th>Phone</th></tr>
  <tr ng-repeat="friend in friends | filter:searchText">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
  </tr>
</table>
<hr>
<label>Any: <input ng-model="search.$"></label> <br>
<label>Name only <input ng-model="search.name"></label><br>
<label>Phone only <input ng-model="search.phone"></label><br>
<label>Equality <input type="checkbox" ng-model="strict"></label><br>
<table id="searchObjResults">
  <tr><th>Name</th><th>Phone</th></tr>
  <tr ng-repeat="friendObj in friends | filter:search:strict">
    <td>{{friendObj.name}}</td>
    <td>{{friendObj.phone}}</td>
  </tr>
</table>

Ví dụ lọc filter angular dạng copy data json

Ví dụ có 1 table $scope.chungtu với 100 bảng ghi
Tạo 1 chungtu_loc dạng copy


$scope.chungtu_loc = $scope.chungtu.filter
    (
        obj =>  obj.DienGiai.toLowerCase().includes(x)
    );
            
       $scope.chungtu_loc.forEach(function(data, index) {
        //sum
            $scope.SUM_ThanhTien +=data.ThanhTien;
        }); //forEach

CHÚ Ý:   Nếu cột DienGiai NULL thì sẽ phát sinh lỗi

 $scope.chungtu_loc = $scope.chungtu.filter
    (     
        obj => isIncludesLowerCase( obj.TenKhachHang, "Từ tim")
    );

function isIncludesLowerCase(vl,str)
{
    if(vl==null) vl="";
    return vl.toLowerCase().includes(str) ;
}

**** Viết hàm lọc trả về kết quả 1 côt chỉ định trong angular

 

  $scope.getTenTinhTrang_From_ChungTu = function (idTT) {
      //  $scope.timkiem= x;
      
         $scope.chungtu_Find_OBJ = $scope.chungtu_tt.filter(
            obj =>  obj.TinhTrang===idTT
         );
         if($scope.chungtu_Find_OBJ.length>0 )
            return $scope.chungtu_Find_OBJ[0].MoTaTinhTrang;   
         else
            return "";        
   }; //getTenTinhTrang_From_ChungTu

  // Ví dụ: filter và Foreach
   $scope.khuvuc_trong_CHON = $scope.khuvuc_trong.filter(
            obj =>  obj.Chon==true
         );
        // alert( JSON.stringify(  $scope.khuvuc_trong_CHON )  );
           $scope.khuvuc_trong_CHON.forEach(function(data, index) {
                //alert( JSON.stringify(  data )  );
                alert(data.TenKhuVuc);
        });

 

* Tham khảo thêm filter

 

Ví dụ tạo hàm filter angular nâng cao riêng


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-sanitize.js"></script>
<div ng-app="myApp" ng-controller="myController">
 <input type="text" class="form-control"  placeholder="Lọc dữ liệu" ng-model="timkiem">
    <table border="1">
        <thead>
            <tr>
                <th>Order</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="data in datas | filter: timkiem">
                <td>{{ $index + 1 }}</td>
                <td>{{ data.price|currency }}</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <!-- here is the magic -->
                <th>{{ datas|total }} items</th>
                <th>&sum; {{ datas|total:'price'|currency }}</th>
            </tr>
        </tfoot>
    </table>
</div>


<script>
var myApp = angular.module('myApp', []);

myApp.filter('total', function () {
alert('x');
            return function (input, property) {
                var i = input instanceof Array ? input.length : 0;
                if (typeof property === 'undefined' || i === 0) {
                    return i;
                } else if (isNaN(input[0][property])) {
                    throw 'filter total can count only numeric values';
                } else {
                    var total = 0;
                    while (i--)
                        total += input[i][property];
                    return total;
                }
            };
        })

    .controller('myController', ['$scope',
            function($scope) {
                $scope.datas = [
                    {
                       price: 55
                    },
                    {
                       price: 72
                    },
                    {
                       price: 43
                    }
                ];
            }]);

</script>