使用angularjs过滤器突出显示搜索结果

时间:2017-12-21 16:19:00

标签: angularjs search highlight angularjs-filter

我有一个简单的表格,通过点击“附加”按钮添加下一行。

我需要突出显示搜索输入字段与表输入字段之间的匹配。

尝试使用highlight过滤器来实现此目的,但它运行时出现错误:

"TypeError: Cannot read property 'replace' of undefined"

我该如何解决?示例代码如下:

var app = angular.module("myApp",[]);

            app.filter('highlight', function($sce) {
                return function(text, phrase) {
                if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
                '<span class="highlighted">$1</span>')
                return $sce.trustAsHtml(text)
                }
            });

            app.controller("myCtrl", ['$scope', 'highlightFilter', function($scope, highlightFilter){
                $scope.arr = [];
                $scope.append = function(){
                    var x = {};
                    x.data1 = "";
                    x.data2 = "";
                    $scope.arr.push(x); 
                };
            }]);
<!DOCTYPE html>
<html>
    <head>
        <title>Author's List</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
        <link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <style>
            .highlighted { background: yellow }
        </style>
    </head>
    <body ng-controller="myCtrl" ng-app="myApp">
        <div class="container">
            <div class="btn-group">
                <button ng-click ="append()" type="button" class="btn btn-default">Append</button>
                <input type="text" placeholder="Search" ng-model="search.text">
                <ul>
                    <div ng-repeat="x in arr | filter:search.text" ng-bind-html="x.text | highlight:search.text"></div>
                </ul>
            </div>
            <form name ="myForm" novalidate> 
                <table class="table table-bordered">
                    <tr>
                        <th>data1</th>
                        <th>data2</th>
                    </tr>
                    <tr ng-repeat="x in arr">
                        <td><input ng-model="x.data1" required type="text" class="form-control"></td>
                        <td><input ng-model="x.data2" required type="text" class="form-control"></td>
                    </tr>
                </table>
            </form>
        </div>
           </body>
</html>    

1 个答案:

答案 0 :(得分:1)

此处的问题是您的过滤器将输入文本作为第一个参数,但您传递的是未在模型上定义的字段:Range("I & (r3 + 3):J & VeryLastRow2").Select 。您有字段Range("I" & (r3 + 3) & ":J" & VeryLastRow2).Select ng-bind-html="x.text | highlight:search.text"但不是data1,这就是您收到上述错误的原因。

您的过滤器实际上正在运行,但您必须将适当的输入参数传递给它:

&#13;
&#13;
data2
&#13;
text
&#13;
&#13;
&#13;