In Angular, we should not try to modify the content of the DOM directly. When we need to update the content of the DOM, what we should modify is actually our data model, that is, the data in $scope. Angular will help us display the modified data on the page.
However, in some cases, for example, we have a search box that hopes to highlight the search keywords in the main text, it will feel more difficult at this time, and filter can help us deal with this situation.
In fact, many times, our data cannot be output directly to the DOM. Typically, such as dates, currency, etc., we usually need to format our internal data and then output it to the page. In Angular, this work is achieved through filter.
filter is a module-level service. After definition, it can be used directly within the entire module, with extremely high reusability.
To illustrate the problem, let me review it firstEnter AngularJs(7) filter (filter)Explain the filter and then explain in detail how to deal with search keyword highlighting issues. You can start directly from the Custom Filters section.
1. Usage of filters
1. Use in the template
We can use filter directly in {{}}, followed by the expression and split it with |. The syntax is as follows:
{{ expression | filter }}
You can also use multiple filters in conjunction, and the output of the previous filter will be used as the input of the next filter.
{{ expression | filter1 | filter2 | ... }}
The filter can receive parameters, and the parameters are separated by:.
{{ expression | filter:argument1:argument2:... }}
In addition to formatting the data in {{}}, we can also use filters in instructions, such as filtering the array array first, and then looping out the output:
<span ng-repeat="a in array | filter ">
2. Use in controller and service
We can also use filters in our js code, which is the dependency injection we are familiar with. For example, I want to use a currency filter in a controller, just inject it into that controller.
('testC',function($scope,currencyFilter){ $ = currencyFilter(123534); }
Use {{num}} in the template to output $123,534.00 directly! The same is true for using filter in services.
At this time, you may have doubts. If I want to use multiple filters in the controller, would it take to inject one by one? Wouldn't it be too difficult? Don't worry, little brother~ng provides a $filter service to call the required filter. You only need to inject a $filter. The usage method is as follows:
('testC',function($scope,$filter){ $ = $filter('currency')(123534); $ = $filter('date')(new Date()); }
2. Built-in filter
1. Currentcy, using currency, you can format numbers as currency, the default is the dollar sign, you can pass in the required symbol yourself
{{num | currency : '¥'}}
2. date, native js has limited formatting capabilities for dates, and the date filter provided by ng can basically meet general formatting requirements.
{{date | date : 'yyyy-MM-dd hh:mm:ss EEEE'}}
3. filter, please note that the name of this filter is filter, don’t mess it up. Used to process an array, and then you can filter out elements containing a substring and return as a subarray. It can be an array of strings or an array of objects. If it is an array of objects, the value of the attribute can be matched. It receives a parameter that defines the matching rules for the substring.
$ = [ {name:'kimi',age:3}, {name:'cindy',age:4}, {name:'anglar',age:4}, {name:'shitou',age:6}, {name:'tiantian',age:5} ];
Custom helper functions.
$ = function(e){return >4;}
Use filter filter
{{ childrenArray | filter : 'a' }} //The matching attribute value contains a{{ childrenArray | filter : 4 }} //The matching attribute value contains 4{{ childrenArray | filter : {name : 'i'} }} //The parameter is an object, matching the name attribute containing i{{childrenArray | filter : func }} //Parameters are functions,Specify returnage>4of
4. json, format the json object. The json filter can format a js object into a json string. The function is the same as we are familiar with ().
{{ jsonTest | json}}
5. limitTo, limitTo filter is used to intercept arrays or strings, and receives a parameter to specify the intercepted length. Only intercepts from the beginning of an array or string
{{ childrenArray | limitTo : 2 }} //The first two items in the array will be displayed
6. lowercase, convert to lowercase. Convert data to all lowercase.
7. uppercase, convert to uppercase.
8. number, format the number. The number filter can be split to a number with thousands, like this, 123,456,789. Receive a parameter at the same time, and you can specify that the small float type retains several decimal places:
{{ num | number : 2 }}
9. OrderBy sorting. The orderBy filter can sort elements in an array and receive a parameter to specify the sorting rules. The parameter can be a string representing sorting by the name of the attribute. It can be a function that defines sorting properties. It can also be an array, which means sorting by the attribute values in the array in turn (if the values compared by the first item are equal, then compare by the second item).
<div>{{ childrenArray | orderBy : 'age' }}</div> //Sort by age attribute value<div>{{ childrenArray | orderBy : orderFunc }}</div> //Sort by the return value of the function<div>{{ childrenArray | orderBy : ['age','name'] }}</div> //ifagesame,according tonameSorting
3. Custom filter
Let’s first define a filter without parameters. The first example comes from the official Angular documentation.
We want to check whether the data is true, if it is true, it will be displayed as a ✘, otherwise, it will be displayed as ✘, in Unicode, \u2713 -> ✘, \u2718 -> ✘, so, all we need to do is check whether the data is true, and then convert it into these two special characters for output.
('checkmark', function() { return function(input) { return input ? '\u2713' : '\u2718'; }; });
The filter can also have parameters, such as the built-in filter that can format currency or date.
Behind the filter, the filter parameters are separated by a colon (:). In the filter, this parameter can be obtained. If there are multiple parameters, continue to be separated by a colon (:) , so the filter can have multiple parameters.
The following implements a filter that truncates super long strings.
("truncate", function(){ return function(text, length){ if (text) { var ellipsis = > length ? "..." : ""; return (0, length) + ellipsis; }; return text; } });
4. Define the highlight filter
We hope that the keywords we searched will be highlighted in the text. The text is the first parameter of the filter, and the second parameter is the search keyword. In this way, our filter will have two parameters.
The principle of highlighting is very simple. Just use the span mark to isolate the content that needs to be highlighted, and add a special class to describe it.
("highlight", function($sce, $log){ var fn = function(text, search){ $("text: " + text); $("search: " + search); if (!search) { return $(text); } text = encodeURI(text); search = encodeURI(search); var regex = new RegExp(search, 'gi') var result = (regex, '<span class="highlightedText">$&</span>'); result = decodeURI(result); $("result: " + result ); return $(result); }; return fn; });
$sce, and $log are two services provided by angular, where the $sce service requires the ngSanitize module. For this module, please refer to: angular-ngSanitize module-$sanitize service details
5. Define service objects
Our page may be complicated and requires entering keywords in one controller. However, we need to use this keyword in multiple controllers for filtering. How to deal with it? Using services can solve this problem.
In Angular, a service is a singleton object. We can directly define a service object using factory.
("notifyService", function(){ var target = { search:"key" }; return target; });
Where you need to use this object, you can get this object by directly injecting it.
6. Define search controller
In the search controller, we want the user to provide search keywords. To facilitate inspection, we will display the user's input.
<div ng-controller="tools"> <div> <input type="text" ng-model="" value=""/> </div> <div> {{}} </div> </div>
In the implementation of the controller, we inject the service object directly into the controller and then bind it to the current $scope so that the binding is implemented in the current controller.
("tools", function($scope, notifyService){ $ = notifyService; });
Now, we can directly enter the search keyword, which will be saved to the service object, and this service object can be accessed in each controller in the current module.
7. Use filter in content controller
Now, we have filters, and we can also directly obtain search keywords through the service object. Now we can use them by combining them. In text is our main content.
<div ng-controller="search"> <div ng-bind-html="text | highlight:"> </div> </div>
Let's take a look at where highlight and come from.
("search", function($scope, $log, notifyService){ $ = "hello, world. hello, world. hello, world."; $ = notifyService; })
In order to use search keywords in the current controller, the key is that when the search keyword changes, it also needs to be updated automatically. We bind the service object to the current $scope, which is the referenced name is notify.
In this way, in complex pages, we may have multiple controllers. In each controller that needs to be highlighted, we only need to inject the service object to directly obtain the current search keywords. In conjunction with the filter, we can directly realize global highlighting.
8. Summary
Combining filters and service objects, we implement keyword highlighting of the content in the entire page in a complex page. The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.