2016-09-02 1 views
0

Я сохранил входное текстовое значение в переменной с именем id = search-query. И затем я просматриваю данные JSON, чтобы найти какой-либо соответствующий результат, а затем выводить результат на экран. Есть ли способ, которым я могу выделить слово, соответствующее запросу query-query.val? Я попытался использовать ng-bind-html вместо этого, но он не выводит результаты.regex и угловые для форматирования слов, которые соответствуют запросу

<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, but does 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) { 

      // For the following line, is there a way which I can bold the word which match the 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; 
     } 
    }); 
} 
+0

Вы можете попробовать это ' {{}} result.name'. 'ng-bind-html' свяжет строку html с элементом span. –

+0

спасибо, но это не сработает. Он выводит тег формата как текст в html. Exp: «Neuberger Berm a n" – user21

ответ

1

Один подход заключается в использовании фильтра в сочетании с нг-Bind-HTML. Фильтр в моем plnkr example скопирован непосредственно из директивного кода типа , поэтому я не беру на это кредит :) Но другая часть этого - использовать ng-модель для поискового запроса, а не искать его с помощью jquery , Надеюсь, это поможет.

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 the whole query string and replace it with the string that will be used to match 
    // the results, for example if the capture is "a" the result will be \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 the user about the danger 
    } 
    matchItem = query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag 
    if (!isSanitizePresent) { 
     matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive 
    } 
    return matchItem; 
    }; 
}); 

 Смежные вопросы

  • Нет связанных вопросов^_^