欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

angular过滤器 -- 关键字高亮显示

程序员文章站 2022-05-18 20:45:47
...

前端处理使给定关键字在文本中高亮显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>filterTest</title>
</head>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myController">
<div ng-bind-html="textLight | highLightFilter:'高亮'"></div>
</body>
<style>
    .pink{
        background: #ddd;
    }
</style>
<script>
    var app = angular.module('myApp', []);
    app.controller('myController', function($scope) {
        $scope.textLight="这是高亮显示";
    });
    app.filter("highLightFilter", function($sce){
        return function(text, search){
            if (!search) {
                return $sce.trustAsHtml(text);
            }
            var regex = new RegExp(search, 'gi')
            var result = text.replace(regex, '<span class="pink">$&</span>');
            return $sce.trustAsHtml(result);
        };
    });
</script>
</html>
显示结果如下:

angular过滤器 -- 关键字高亮显示