如果搜索文本与数组中的可用文本匹配,如何突出显示数据?

时间:2016-07-28 14:59:32

标签: javascript angularjs angularjs-filter

我已经使用$scope.data在屏幕上显示ng-repeat,我有一个输入,用户可以从$scope.data进行搜索,所以如果用户搜索文本与{匹配的话,我会创建过滤器{1}}突出显示该文本,它没有抛出任何异常,但也没有突出显示文本,我对angularjs过滤器相当新,帮助将非常感激。提前谢谢。

ctrl.js

$scope.data

main.html中

$scope.data = ["Lorem Ipsum is simply dummy text", "Lorem Ipsum is simply dummy text"];

filter.js

<div class="row search-input-margin">
    <div class="col-md-12 form-group">
        <div class="col-md-3">
            <label for="search">Search Logs:</label>
        </div>
        <div class="col-md-9">
            <input type="text" class="form-control" id="search" ng-model="vm.searchLog">
        </div>
    </div>
</div>

    <div class="row">
            <div class="col-md-12">
                <ul style="list-style: none;">
                    <li ng-repeat="message in data track by $index"><span><strong>Log:</strong></span><span>{{message}}</span></li>
                </ul>
            </div>
            <div>
                <ul>
                    <!-- filter code -->
                    <div ng-repeat="item in data | filter:vm.searchLog"
                         ng-bind-html="item | highlight:vm.searchLog">
                    </div>
                </ul>
            </div>
        </div>

2 个答案:

答案 0 :(得分:4)

您缺少.highlighted

的样式

&#13;
&#13;
var app = angular.module("sa", []);

app.controller("FooController", function($scope) {
  $scope.data = ["Lorem Ipsum is simply dummy text", "Lorem Ipsum is simply dummy"];
});

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)
  }

});
&#13;
.highlighted {
  font-weight: bold
    }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">


<div ng-app="sa" ng-controller="FooController as vm">

  <div class="row search-input-margin">
    <div class="col-md-12 form-group">
      <div class="col-md-3">
        <label for="search">Search Logs:</label>
      </div>
      <div class="col-md-9">
        <input type="text" class="form-control" id="search" ng-model="vm.searchLog">
      </div>
    </div>
  </div>

  <ul>
    <!-- filter code -->
    <li ng-repeat="item in data | filter: vm.searchLog" ng-bind-html="item | highlight:vm.searchLog">
    </li>
  </ul>


</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<div ng-repeat="item in data | filter:vm.searchLog"
         ng-bind-html-unsafe="item | highlight:vm.searchLog">
</div>

为什么不在这里使用ng-bind-html-unsafe?如果您使用的是ng-bind-html,则需要加载angular-sanitize.min.js

此处有更详细的链接: AngularJS : Insert HTML into view