如何隐藏与我的过滤器不匹配的对象的其他元素?

时间:2018-04-11 12:48:22

标签: javascript angularjs

我目前有一个过滤器,我在其中使用title和name的属性查看文本字段中的对象。如果有匹配,则单词以黄色突出显示。

我想知道怎么做,如果有巧合,我的对象的其他元素消失,只显示巧合的对象。

enter image description here

这是我的代码:

https://plnkr.co/edit/Lb56FtZxdIyMNluwCSm8?p=preview

  $scope.data = [{
    text: "<< ==== Put text to Search ===== >>"
  }];

  $scope.data = [{
    title: "Bad",
    name: 'bill'
  }, {
    title: "Good",
    name: 'Goe'
  }, {
    title: "Great",
    name: 'Brad'
  }, {
    title: "Cool",
    name: 'yan'
  }, {
    title: "Excellent",
    name: 'mikle'
  }, {
    title: "Awesome",
    name: 'mosa'
  }, {
    title: "Horrible",
    name: 'morteza'
  }];

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

  <input type="text" placeholder="Search" ng-model="search">  
  <ul>
    <!-- filter code -->
    <li ng-repeat="item in data">
      <p><span>Title: </span><span ng-bind-html="item.title | highlight:search"></span></p>
      <p><span>Name: </span><span ng-bind-html="item.name | highlight:search"></span></p>
    </li>
  </ul>

感谢

1 个答案:

答案 0 :(得分:3)

通过搜索键过滤数组,因此只有匹配的对象才会显示在用户界面中ng-repeat="item in data | filter: search"

<li ng-repeat="item in data | filter: search">
  <p><span>Title: </span><span ng-bind-html="item.title | highlight:search"></span></p>
  <p><span>Name: </span><span ng-bind-html="item.name | highlight:search"></span></p>
</li>