i have stored input text value variable id name=search-query. , searching through json data find matching result , output result on screen. there way can bold word match search-query.val? have tried use ng-bind-html instead doesn't output results.
<body ng-app="products" ng-controller="ctrl"> <input type="text" id="search-query" name="query" placeholder="enter product name"></input> <tbody> <tr ng-repeat="result in searchresult|orderby:order:reverse" > <td > <a ng-href="{{result.link}}" target="_blank"> //used ng-bind-html or ng-bind, not works <span ng-bind-html="result.name" target="_blank"></span> </a> </td> <td ng-bind="result.type"></td> </tr> </tbody>
var app2 = angular.module('products', []); app2.controller('ctrl', function($scope) { $scope.searchresult = []; $scope.submit = function(){ var search = $("#search-query").val(); $.each(json.products, function(i, v) { var regex = new regexp(search, "i"); if (v.name.search(regex) != -1) { // following line, there way can bold word match search-query.val? var name = v.name.replace(search, "<b>search</b>"); // doesn't work $scope.searchresult.push({ name:name, type: v.type, link: v.url }); return; } }); }
one approach use filter in combination ng-bind-html. filter in plnkr example copied directly angular bootstrap typeahead directive code, i'm not taking credit :) other part of use ng-model search term instead of looking using jquery. hope helps.
markup:
<input type="text" ng-model="search.name"> <ul> <li ng-repeat="item in items | filter: search.name"> <span ng-bind-html="item | highlight:search.name"></span> </li> </ul>
javascript:
var app = angular.module('plunker', ['ngsanitize']); app.controller('mainctrl', function($scope) { $scope.search = { name: '' }; $scope.items = ['jane','john','sam','jennifer','martha']; }); app.filter('highlight', function($sce, $injector, $log) { var issanitizepresent; issanitizepresent = $injector.has('$sanitize'); function escaperegexp(querytoescape) { // regex: capture whole query string , replace string used match // results, example if capture "a" result \a return querytoescape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } function containshtml(matchitem) { return /<.*>/g.test(matchitem); } return function(matchitem, query) { if (!issanitizepresent && containshtml(matchitem)) { $log.warn('unsafe use of typeahead please use ngsanitize'); // warn user danger } matchitem = query ? ('' + matchitem).replace(new regexp(escaperegexp(query), 'gi'), '<strong>$&</strong>') : matchitem; // replaces capture string same string inside of "strong" tag if (!issanitizepresent) { matchitem = $sce.trustashtml(matchitem); // if $sanitize not present pack string in $sce object ng-bind-html directive } return matchitem; }; });
Comments
Post a Comment