Keyword highlighting for search in Angular

Source: Internet
Author: User

In Angular, we should not try to modify the contents of the DOM directly, when we need to update the DOM content, we should modify the data model, that is, the data in the $scope, Angular will help us to display the modified data in the page.

However, in some cases, such as we have a search box, we want to highlight the search keyword in the body, this time will feel more difficult, filter can help us deal with this situation.

In fact, most of the time, our data can not be directly exported to the DOM, typical such as date, or currency, etc., usually need to format our internal data, and then output to the page, in Angular, this work is done through the filter.

Filter is a module-level service that, after definition, can be used directly within the entire module, with very high reusability.

In order to illustrate the problem, first large section copy of the LV Leopard into the Angularjs (seven) filter (filter) Explain the filter, and then detailed how to deal with the search keyword highlighting problem. You can start directly from the Custom Filter section.

1. Usage of the filter 1. Used in templates

We can use filter directly in {{}}, followed by an expression | The syntax for partitioning is as follows:

{{expression | filter}}

You can also use multiple filter, and the output from the previous filter will be the input to the next filter.

{{expression | filter1 | filter2 | ...}}

Filter can receive parameters, parameters are separated by:

{{expression | filter:argument1:argument2: ...}}

In addition to formatting the data in {{}}, we can also use the filter in the instruction, such as filtering the array arrays first, and then looping the output:

<ng-repeat= "A In array | filter">
2. Use in controller and service

We can also use filters in our JS code, the way we are familiar with dependency injection, for example, I want to use the currency filter in the controller, just inject it into the controller.

App.controller (' TESTC ',function($scope, currencyfilter) {    = Currencyfilter (123534);  }

Using {{num}} in the template can output $123,534.00 directly! Using filter in a service is the same thing.

You may have doubts at this point, if I want to use more than one filter in the controller, is it too much to inject one? Little Brother Mo Anxious ~ng provides a $filter service to invoke the desired filter, you only need to inject a $filter is enough, use the following method:

App.controller (' TESTC ',function($scope, $filter) {    = $filter (' Currency ') (123534= $ Filter (' Date ') (new  date ());  }
2. Built-in filter

1. currentcy, using currency can format the number as currency, default is the dollar sign, you can pass the required symbol yourself

{{num | currency: ' ¥ '}}

2. Date, native JS has limited formatting capabilities for dates, and the date filter provided by Ng basically satisfies the general formatting requirements.

{{date | date: ' YYYY-MM-DD hh:mm:ss eeee '}}

3. Filter, note that this filter is named filter, do not confuse. Used to process an array, and then filter out the elements containing a substring to return as a subarray. Can be an array of strings, or an array of objects. If it is an array of objects, you can match the value of the property. It receives a parameter that defines the matching rules for the substring.

$scope. Childrenarray = [        {name: ' Kimi ', Age:3},        {name:' Cindy ', Age:4},        {name: ' Anglar ', Age:4},        {name:' Shitou ', Age:6},        {name:' Tiantian ', Age:5}    ];

A custom helper function.

function (e) {return e.age>4;}

Using the filter filter

// match attribute values that contain a {{Childrenarray | filter:4}}  // The match attribute value contains 4 of the // parameter is an object that matches the name attribute that contains I {{Childrenarray | filter:func}}  // parameter is a function that specifies the return age>4 of the

4. JSON, format the JSON object. The JSON filter can format a JS object as a JSON string. The role is the same as the json.stringify () we are familiar with.

{{jsontest | json}}

5. LimitTo, LimitTo filters are used to intercept arrays or strings, and receive a parameter to specify the length of the Intercept. Can only be intercepted from the beginning of an array or string

{{Childrenarray | limitto:2}}  // The first two items in the array are displayed

6. Lowercase, convert to lowercase. Convert the data to all lowercase.

7. Uppercase, convert to uppercase.

8. Number, format the numbers. The number filter can be divided into thousands, like this, 123,456,789. While receiving a parameter, you can specify a small float type to retain several decimals:

{{num | number:2}}

9. Sort by order, orders by filter you can sort the elements in an array, receive a parameter to specify the collation, and the argument can be a string representing the sort by the property name. Can be a function that defines a sort property. It can also be an array that is sorted by the property values in the array (if the values are equal by the first item and then the second one),

<Div>{{Childrenarray | by: ' Age '}}</Div>//Sort by age property value<Div>{{Childrenarray | orderby:orderfunc}}</Div>//Sort by the return value of the function<Div>{{Childrenarray |: [' age ', ' name ']}}</Div>If age is the same, sort by name
3. Custom Filter

Let's first define a filter without parameters. The first example comes from Angular's official documentation.

We want to check if the data is true, and if so, show it as one? , otherwise, shown as, in Unicode,--, \u2713 \u2718 So, all we need to do is check that the data is true and then convert it to these two special characters for output.

function () {  returnfunction(input) {    return input? ' \u2713 ': ' \u2718 ';  };});

Filters can also have parameters, such as a built-in filter that can format currency or date.

After the filter, use a colon (:) Separated is the filter parameters, in the filter, you can get this parameter, if there are more than one parameter, continue to use the colon (:) , so the filter can have multiple parameters.

The following implements a filter that truncates an extra-long string.

function () {    returnfunction(text, length) {        if  (text) {             var ellipsis = text.length > length? "..." : "";             return text.slice (0, length) + ellipsis;        };         return text;            }});
4. Define the Highlight filter

We want the search keyword highlighted in the text, the body is the first parameter of the filter, the second parameter is the search keyword, so that our filter will have two parameters.

The principle of highlighting is simple, isolating the content that needs highlighting with a span tag, plus a special class to describe it.

App.filter ("Highlight",function($sce, $log) {varfn =function(text, search) {$log. info ("Text:" +text); $log. Info ("Search:" +search); if(!search) {            return$sce. trustashtml (text); } text=encodeURI (text); Search=encodeURI (search); varRegex =NewREGEXP (Search, ' GI ')        varresult = Text.replace (regex, ' <span class= ' highlightedtext ' >$&</span> '); Result=decodeURI (Result); $log. Info ("Result:" +result); return$sce. trustashtml (Result);    }; returnfn;});

$sce, and $log are the two services provided by angular, where the $SCE service requires the use of ngsanitize modules. For this module, you can refer to: Angular-ngsanitize module-$sanitize service detailed

5. Defining the Service object

Our page may be very complex, you need to enter a keyword in a controller, but you need to use this keyword in multiple controllers to filter, how to deal with it? Using the service can solve this problem.

In Angular, a service is a singleton object, and we use factory to define a service object directly.

function () {    var target = {        search:' key '    };     return target;});

Where this object needs to be used, direct injection will get the object.

6. Define the search Controller

In the search controller, we want the user to provide the search keyword. For the convenience of inspection, we will show the user's input by the way.

        <DivNg-controller= "Tools">            <Div>                <inputtype= "text"Ng-model= "Notify.search"value=""/>            </Div>            <Div>{{Notify.search}}</Div>        </Div>

Controller implementation, we inject the service object directly into the controller and bind it to the current $scope to implement the binding in the current controller.

function ($scope, Notifyservice) {    = notifyservice; });

Now, we can enter the search keyword directly, this keyword will be saved to the service object, you can access the service object in each controller in the current module.

7. Using the filter in the content Controller

Now that we have filters, we can get search keywords directly from the service object, and now we can use them together. Text is the content of our text.

        <ng-controller= "search">            <   ng-bind-html= "text | highlight:notify.search">            </Div >        </ Div >

Let's see where highlight and Notify.search come from.

function ($scope, $log, Notifyservice) {    = "Hello, world.") Hello, world. Hello, world. " ;     = Notifyservice; })

In order to use the search keyword in the current controller, the key is that when the search keyword changes, we also need to update automatically, we bind the service object to the current $scope, which is the reference name notify.

In this way, in the complex page, we may have multiple controllers, in each need to highlight the controller, we only need to inject the service object, we can directly get to the current search keyword, with the use of filters, you can directly achieve global highlighting.

8. Summary

In combination with filters and service objects, we implement keyword highlighting of content throughout a page in complex pages.

Reference:

About Angularjs (vii) filters (filter)

AngularJS filters in Depth

Angular-ngsanitize Module-Detailed $sanitize service

Keyword highlighting for search in Angular

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.