Web888.vn
  • Shop
  • Blog
Đăng nhập
  • Đăng nhập / Đăng ký

Please enter key search to display results.

Home
  • AngularJS
  • AngularJS
  • Javascript Programming
Filter (filter) in angularJS

Filter (filter) in angularJS

  • 25-07-2022
  • Toanngo92
  • 0 Comments

Mục lục

  • The concept and role of filters in angularJS
  • List of built-in filters in angularJS
    • Currency filter
    • Date filter
    • Lowercase and uppercase
    • Search Filter
  • Custom Filters (self-defined filters)

The concept and role of filters in angularJS

When approaching with pure javascript, we see, when working with data, there are some situations where we will have to convert a rather complicated persistent data type, to take a real example, when we have a variable representing the amount with data type number (float) , if we want to print to the screen in currency format, we will have to do the following steps sequentially:

  • Convert data type to string,
  • Concatenate strings by adding a $ sign after the string
  • Print the string out inside the HTML content (via the innerText property)
  • Repeat the above steps sequentially when the data is updated

With angularJs, we have a filter mechanism to support the model to shorten these tasks, the model does not need to convert the data type, filters will do the work of filtering the data and printing the results as we want. . In short, filters reformat data when presented to the end user

Syntax to use filters in angularJS:

{{expression | filter}}

Filter is injected into the expression via the “|” character. , followed by filter

Filters can be connected as consecutive links, for example:

{{expression | filter | filter}}

In this case, the first filter is used to filter the expression, the second filter continues to filter the value of the first filter.

Note: filter does not change the actual value of the variable, it only changes the end-user display format.

List of built-in filters in angularJS

Some of the popular built-in filters in angularJS:

  • Currency
  • Date
  • Lowercase
  • Uppercase
  • Search
  • …

Currency filter

Used to format the currency for the expression, which will be displayed to the user in the currency format

Docs: https://docs.angularjs.org/api/ng/filter/currency

By default, it will use the format USD Dollars with 2 numbers after the . The example below describes some ways to use filter, at html template layer and script layer, we can use filter under html layer or filter on javascript layer, but html layer way will be more common:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myController"> {{price | currency:'$ '}} <br/> {{price | currency: '$ ' : 0}} <br/> {{price2 | currency:'VND '}} <br/> <input type="number" ng-model="price3" /> <br/> {{changeprice()}} </div> </body> <script> var app = angular.module('myApp',[]); app.controller('myController',($scope,$filter) => { $scope.price = 1000; $scope.price2 = 2000; $scope.price3 = 4000; $scope.changeprice = function(){ bind_model = $filter('currency')($scope.price3, '$ ', 5); return bind_model; } }); </script> </html>

Result when printing to the browser:

However, from my point of view, this filter does not meet VND, because the currency of my country is displayed, but VND is on the right of the number, so this filter will not respond. Of course there is a solution, we can define our own custom filter

Date filter

Docs: https://docs.angularjs.org/api/ng/filter/date

With the date filter, we can represent all date data according to the intention we want when displaying the data to the interface.

Consider the example below to better understand the date filter:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Date filter</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myController"> {{date | date:'dd/MM/yyyy'}} </div> </body> <script> var app = angular.module('myApp',[]); app.controller('myController',($scope) => { $scope.date = Date.now(); console.log($scope.date); }); </script> </html>

Result when printing to the browser:

We see, the javascript layer data is timestamp representing the current time while we are writing code according to UNIX timestamp, but when printing the interface, thanks to the filter mechanism of angularJS, we have printed the date value. readable year.

Not only that, filter date has a lot of options to help you perform different formats, read on the docs to understand more.

Lowercase and uppercase

This filter is used to filter data and reformat it to lowercase or uppercase string

{{expression | lowercase}} {{expression | uppercase}}

Search Filter

Filters are used to find data in a list, which is quite convenient, see the example below to better understand the problem:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Search filter</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myController"> <input type="text" ng-model="search" placeholder="Search"> <table> <tr ng-repeat="x in listUser | filter:search"> <td> {{x.name}} </td> <td> {{x.age}} </td> </tr> </table> </div> </body> <script> var app = angular.module('myApp', []); app.controller('myController', ($scope) => { $scope.listUser = [ { name: "toan", age: 20 }, { name: "huy", age: 21 }, { name: "hieu", age: 22 }, { name: "toan", age: 34 }, ]; }); </script> </html>

Interface when printing to the browser

Custom Filters (self-defined filters)

If the builtin filters are not enough to use, we can completely define a custom directive to filter as we want. Syntax to initialize custom filter:

app.filter('filtername',function(){});

In the example below, I create a filter with the filter used for currency format VND

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myController"> {{price | vndFilter}} </div> </body> <script> var app = angular.module('myApp', []); app.filter('vndFilter', function () { return function (x) { x = x.toString().replace(/B(?=(d{3})+(?!d))/g, ','); // convert float to string decimal thousand separator x += ' VND'; // concat with VND return x; }; }) app.controller('myController', function ($scope) { $scope.price = 5000000; }); </script> </html>

Results when displayed in the browser

Bài viết liên quan:

Expressions in AngularJS
Data binding mechanism in AngularJS
Event handling in angularJS
Route (routing) in angularJS
Form validation in angularJS
Animation in angularJS
Dependency Injection mechanism in angularJS
Factory and Service in angularJS
Install Visual Studio Code for C/C++ programming on Windows and MacOs
Overview of AngularJS
Integrate AngularJS into the project and write hello world application
Controller in AngularJS

THÊM BÌNH LUẬN Cancel reply

Dịch vụ thiết kế Wesbite

NỘI DUNG MỚI CẬP NHẬT

Step-by-step guide to installing Microsoft SQL Server and connecting to the database for beginners

Reasons Why People Are Increasingly Inexperienced in Life

PHP Data Types

Table (table) in SQL Server

Basic data types in C

Giới thiệu

web888.vn là chuyên trang chia sẻ và cập nhật tin tức công nghệ, chia sẻ kiến thức, kỹ năng. Chúng tôi rất cảm ơn và mong muốn nhận được nhiều phản hồi để có thể phục vụ quý bạn đọc tốt hơn !

Liên hệ quảng cáo: [email protected]

Kết nối với web888

© web888.vn - Tech888 Co .Ltd since 2019

Đăng nhập

Trở thành một phần của cộng đồng của chúng tôi!
Registration complete. Please check your email.
Đăng nhập bằng google
Đăng kýBạn quên mật khẩu?

Create an account

Welcome! Register for an account
The user name or email address is not correct.

Your personal data will be used to support your experience throughout this website, to manage access to your account, and for other purposes described in our privacy policy.

Registration confirmation will be emailed to you.
Log in Lost your password?

Reset password

Recover your password
Password reset email has been sent.
The email could not be sent. Possible reason: your host may have disabled the mail function.
A password will be e-mailed to you.
Log in Register
×