AngularJS에서 필터링 된 결과 강조
전화 튜토리얼과 같은 angularJS에서 ng-repeat 및 필터를 사용하고 있지만 페이지에서 검색 결과를 강조하고 싶습니다. 기본 jQuery를 사용하면 입력에서 키에 대한 페이지를 간단히 구문 분석했지만 각도 방식으로 수행하려고합니다. 어떤 아이디어?
내 코드 :
<input id="search" type="text" placeholder="Recherche DCI" ng-model="search_query" autofocus>
<tr ng-repeat="dci in dcis | filter:search_query">
<td class='marque'>{{dci.marque}} ®</td>
<td class="dci">{{dci.dci}}</td>
</tr>
AngularJS v1.2 +에서 그렇게했습니다.
HTML :
<span ng-bind-html="highlight(textToSearchThrough, searchText)"></span>
JS :
$scope.highlight = function(text, search) {
if (!search) {
return $sce.trustAsHtml(text);
}
return $sce.trustAsHtml(text.replace(new RegExp(search, 'gi'), '<span class="highlightedText">$&</span>'));
};
CSS :
.highlightedText {
background: yellow;
}
angular ui-utils는 하나의 용어 만 지원합니다. 범위 함수가 아닌 다음 필터를 사용하고 있습니다.
app.filter('highlight', function($sce) {
return function(str, termsToHighlight) {
// Sort terms by length
termsToHighlight.sort(function(a, b) {
return b.length - a.length;
});
// Regex to simultaneously replace terms
var regex = new RegExp('(' + termsToHighlight.join('|') + ')', 'g');
return $sce.trustAsHtml(str.replace(regex, '<span class="match">$&</span>'));
};
});
그리고 HTML :
<span ng-bind-html="theText | highlight:theTerms"></span>
Angular UI 사용해보기
필터-> Highlite (필터). Keypress 지시문도 있습니다.
index.html
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script src="app.js"></script>
<style>
.highlighted { background: yellow }
</style>
</head>
<body ng-app="Demo">
<h1>Highlight text using AngularJS.</h1>
<div class="container" ng-controller="Demo">
<input type="text" placeholder="Search" ng-model="search.text">
<ul>
<!-- filter code -->
<div ng-repeat="item in data | filter:search.text"
ng-bind-html="item.text | highlight:search.text">
</div>
</ul>
</div>
</body>
</html>
app.js
angular.module('Demo', [])
.controller('Demo', function($scope) {
$scope.data = [
{ text: "<< ==== Put text to Search ===== >>" }
]
})
.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)
}
})
참조 : http://codeforgeek.com/2014/12/highlight-search-result-angular-filter/ 데모 : http://demo.codeforgeek.com/highlight-angular/
angular-bootstrap 에는 표준 하이라이트 필터가 있습니다 .typeaheadHighlight
용법
<span ng-bind-html="text | typeaheadHighlight:query"></span>
범위가 {text:"Hello world", query:"world"}
렌더링 됨
<span...>Hello <strong>world</strong></span>
내 간단한 예제가 이해하기 쉽게 만들었 으면합니다.
app.filter('highlight', function() {
return function(text, phrase) {
return phrase
? text.replace(new RegExp('('+phrase+')', 'gi'), '<kbd>$1</kbd>')
: text;
};
});
<input type="text" ng-model="search.$">
<ul>
<li ng-repeat="item in items | filter:search">
<div ng-bind-html="item | highlight:search.$"></div>
</li>
</ul>
이 스레드에서 @uri의 답변으로 이동하여 단일 문자열 또는 문자열 배열 로 작동하도록 수정했습니다 .
TypeScript 버전 은 다음과 같습니다.
module myApp.Filters.Highlight {
"use strict";
class HighlightFilter {
//This will wrap matching search terms with an element to visually highlight strings
//Usage: {{fullString | highlight:'partial string'}}
//Usage: {{fullString | highlight:['partial', 'string, 'example']}}
static $inject = ["$sce"];
constructor($sce: angular.ISCEService) {
// The `terms` could be a string, or an array of strings, so we have to use the `any` type here
/* tslint:disable: no-any */
return (str: string, terms: any) => {
/* tslint:enable */
if (terms) {
let allTermsRegexStr: string;
if (typeof terms === "string") {
allTermsRegexStr = terms;
} else { //assume a string array
// Sort array by length then join with regex pipe separator
allTermsRegexStr = terms.sort((a: string, b: string) => b.length - a.length).join('|');
}
//Escape characters that have meaning in regular expressions
//via: http://stackoverflow.com/a/6969486/79677
allTermsRegexStr = allTermsRegexStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
// Regex to simultaneously replace terms - case insensitive!
var regex = new RegExp('(' + allTermsRegexStr + ')', 'ig');
return $sce.trustAsHtml(str.replace(regex, '<mark class="highlight">$&</mark>'));
} else {
return str;
}
};
}
}
angular
.module("myApp")
.filter("highlight", HighlightFilter);
};
이것은 JavaScript로 번역됩니다 .
var myApp;
(function (myApp) {
var Filters;
(function (Filters) {
var Highlight;
(function (Highlight) {
"use strict";
var HighlightFilter = (function () {
function HighlightFilter($sce) {
// The `terms` could be a string, or an array of strings, so we have to use the `any` type here
/* tslint:disable: no-any */
return function (str, terms) {
/* tslint:enable */
if (terms) {
var allTermsRegexStr;
if (typeof terms === "string") {
allTermsRegexStr = terms;
}
else {
// Sort array by length then join with regex pipe separator
allTermsRegexStr = terms.sort(function (a, b) { return b.length - a.length; }).join('|');
}
//Escape characters that have meaning in regular expressions
//via: http://stackoverflow.com/a/6969486/79677
allTermsRegexStr = allTermsRegexStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
// Regex to simultaneously replace terms - case insensitive!
var regex = new RegExp('(' + allTermsRegexStr + ')', 'ig');
return $sce.trustAsHtml(str.replace(regex, '<mark class="highlight">$&</mark>'));
}
else {
return str;
}
};
}
//This will wrap matching search terms with an element to visually highlight strings
//Usage: {{fullString | highlight:'partial string'}}
//Usage: {{fullString | highlight:['partial', 'string, 'example']}}
HighlightFilter.$inject = ["$sce"];
return HighlightFilter;
})();
angular.module("myApp").filter("highlight", HighlightFilter);
})(Highlight = Filters.Highlight || (Filters.Highlight = {}));
})(Filters = myApp.Filters || (myApp.Filters = {}));
})(myApp|| (myApp= {}));
;
또는 생성 된 네임 스페이스없이 간단한 JavaScript 구현 을 원하는 경우 :
app.filter('highlight', ['$sce', function($sce) {
return function (str, terms) {
if (terms) {
var allTermsRegexStr;
if (typeof terms === "string") {
allTermsRegexStr = terms;
}
else {
// Sort array by length then join with regex pipe separator
allTermsRegexStr = terms.sort(function (a, b) { return b.length - a.length; }).join('|');
}
//Escape characters that have meaning in regular expressions
//via: http://stackoverflow.com/a/6969486/79677
allTermsRegexStr = allTermsRegexStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
// Regex to simultaneously replace terms - case insensitive!
var regex = new RegExp('(' + allTermsRegexStr + ')', 'ig');
return $sce.trustAsHtml(str.replace(regex, '<mark class="highlight">$&</mark>'));
}
else {
return str;
}
};
}]);
편집 됨 이전에이 사람이 검색입니다 깨진 것 수정을 포함하는 .
또는 정규 표현식의 의미를했던 다른 문자를. 이제 해당 문자가 먼저 이스케이프됩니다.
검색어가 요소에 포함 된 데이터와 관련 될 때 적용되는 ng-class를 사용하십시오.
따라서 반복되는 요소에 대해 ng-class="{ className: search_query==elementRelatedValue}"
조건이 충족되면 클래스 "className"을 요소에 동적으로 적용합니다.
특수 caracter의 문제에 대해서는 이스케이프하면 정규식 검색을 잃을 수 있다고 생각합니다.
이것에 대해 :
function(text, search) {
if (!search || (search && search.length < 3)) {
return $sce.trustAsHtml(text);
}
regexp = '';
try {
regexp = new RegExp(search, 'gi');
} catch(e) {
return $sce.trustAsHtml(text);
}
return $sce.trustAsHtml(text.replace(regexp, '<span class="highlight">$&</span>'));
};
잘못된 정규식은 사용자가 텍스트를 입력하는 것일 수 있습니다.
- 유효 : m
- 유효하지 않음 : m [
- 유효하지 않음 : m [ô
- 유효하지 않음 : m [ôo
- 유효 : m [ôo]
- 유효 : m [ôo] n
- 유효 : m [ôo] ni
- 유효 : m [ôo] nic
- 유효 : m [ôo] nica
@Mik Cox는 어떻습니까?
또 다른 제안 :
app.filter('wrapText', wrapText);
function wrapText($sce) {
return function (source, needle, wrap) {
var regex;
if (typeof needle === 'string') {
regex = new RegExp(needle, "gi");
} else {
regex = needle;
}
if (source.match(regex)) {
source = source.replace(regex, function (match) {
return $('<i></i>').append($(wrap).text(match)).html();
});
}
return $sce.trustAsHtml(source);
};
} // wrapText
wrapText.$inject = ['$sce'];
// use like this
$filter('wrapText')('This is a word, really!', 'word', '<span class="highlight"></span>');
// or like this
{{ 'This is a word, really!' | wrapText:'word':'<span class="highlight"></span>' }}
나는 비판에 개방적이다! ;-)
이것도 제가 다루고있는 것이기 때문에 물어 주셔서 감사합니다.
하지만 두 가지 :
First, The top answer is great but the comment on it is accurate that highlight() has problem with special characters. That comment suggests using an escaping chain which will work but they suggest using unescape() which is being phased out. What I ended up with:
$sce.trustAsHtml(decodeURI(escape(text).replace(new RegExp(escape(search), 'gi'), '<span class="highlightedText">$&</span>')));
Second, I was trying to do this in a data bound list of URLs. While in the highlight() string, you don't need to data bind.
Example:
<li>{{item.headers.host}}{{item.url}}</li>
Became:
<span ng-bind-html="highlight(item.headers.host+item.url, item.match)"></span>
Was running into problems with leaving them in {{ }} and getting all sorts of errors.
Hope this helps anybody running into the same problems.
If you are using the angular material library there is a built in directive called md-highlight-text
From the documentation:
<input placeholder="Enter a search term..." ng-model="searchTerm" type="text">
<ul>
<li ng-repeat="result in results" md-highlight-text="searchTerm">
{{result.text}}
</li>
</ul>
Link to docs: https://material.angularjs.org/latest/api/directive/mdHighlightText
강조 표시에 대한 내 솔루션은 angular-ui-tree 요소와 함께 사용했습니다 : https://codepen.io/shnigi/pen/jKeaYG
angular.module('myApp').filter('highlightFilter', $sce =>
function (element, searchInput) {
element = element.replace(new RegExp(`(${searchInput})`, 'gi'),
'<span class="highlighted">$&</span>');
return $sce.trustAsHtml(element);
});
CSS 추가 :
.highlighted {
color: orange;
}
HTML :
<p ng-repeat="person in persons | filter:search.value">
<span ng-bind-html="person | highlightFilter:search.value"></span>
</p>
검색 입력을 추가하려면 :
<input type="search" ng-model="search.value">
참조 URL : https://stackoverflow.com/questions/15519713/highlighting-a-filtered-result-in-angularjs
'Development Tip' 카테고리의 다른 글
PHP에서 문자열이 base64인지 확인하는 방법 (0) | 2021.01.05 |
---|---|
부드러운 곡선 그리기-필요한 방법 (0) | 2021.01.05 |
모바일보기에서만 div 태그를 숨기시겠습니까? (0) | 2021.01.05 |
간단한 방명록 django : __init __ ()는 1 개의 위치 인자를 받지만 2 개가 주어졌습니다. (0) | 2021.01.05 |
Mailchimp의 API v3을 사용하여 목록에 구독자 추가 (0) | 2021.01.05 |