AngularJS中如何隐藏对象中不符合筛选条件的元素?
Solution to Filter and Highlight Matching Items
Hey there! Let's adjust your code so that only the items matching your search term are displayed, while keeping the yellow highlight for the matched keywords. Here's how to do it step by step:
1. Update the Controller with a Custom Filter Function
First, we'll add a filter function to your controller that checks if an item's title or name contains the search term. This will determine which items get shown:
angular.module('app', []) .controller('MainCtrl', function($scope) { // Your existing data array (replace with your actual data) $scope.data = [ { title: "AngularJS Guide", name: "John Doe" }, { title: "JavaScript Basics", name: "Jane Smith" }, { title: "CSS Tricks", name: "Bob Johnson" } ]; // Custom filter function to match title or name $scope.searchFilter = function(item) { // Show all items if search text is empty if (!$scope.searchText) return true; const searchTerm = $scope.searchText.toLowerCase(); // Check if title or name includes the search term (case-insensitive) const matchesTitle = item.title?.toLowerCase().includes(searchTerm); const matchesName = item.name?.toLowerCase().includes(searchTerm); return matchesTitle || matchesName; }; }) // Existing highlight filter (keep this to add yellow background) .filter('highlight', function($sce) { return function(text, search) { if (!search) return $sce.trustAsHtml(text); // Create regex to find matches (case-insensitive, global) const regex = new RegExp(search, 'gi'); // Wrap matched text in a yellow span return $sce.trustAsHtml(text.replace(regex, '<span style="background-color: yellow">$&</span>')); }; });
2. Modify the HTML to Use the Filter
Update your ng-repeat to use the custom filter, and apply the highlight filter to the title and name properties:
<div ng-app="app" ng-controller="MainCtrl"> <input type="text" ng-model="searchText" placeholder="Search title or name..."> <div ng-repeat="item in data | filter: searchFilter"> <h3 ng-bind-html="item.title | highlight: searchText"></h3> <p ng-bind-html="item.name | highlight: searchText"></p> <hr> </div> </div>
Key Changes Explained
- Custom Filter Function: The
searchFilterfunction returnstrueonly for items where eithertitleornamecontains the search term (case-insensitive). If the search box is empty, it returnstruefor all items, so everything is displayed. - Highlight Filter: The existing
highlightfilter wraps matched keywords in a<span>with a yellow background. We useng-bind-htmlto render the HTML safely. - Filtered ng-repeat: By adding
| filter: searchFilterto the ng-repeat, we ensure only matching items are rendered in the DOM.
This setup will hide all non-matching items when a search term is entered, and show all items when the search box is empty. The matched parts of title and name will stay highlighted in yellow.
内容的提问来源于stack exchange,提问作者yavg
相关产品推荐
相关产品推荐

