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

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

<!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 | highlight:'高亮'"></div>
</body>
<style>
    .pink{
        background: #ddd;
    }
</style>
<script>
    var app = angular.module('myApp', []);
    app.controller('myController', function($scope) {
        $scope.textLight="这是高亮显示";
    });
    app.filter("highlight", 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>

显示结果如下:

原文地址:https://www.cnblogs.com/huangxingquan/p/7598404.html