ng-repeat

时间:2016-02-17 17:59:56

标签: javascript html angularjs filter ng-bind-html

我制作了一个自定义自动提示组件,我点击了一个带有搜索字词的网络服务,它会返回我显示的建议列表。

我的问题是,我想在列表中加粗匹配的术语,而角度与额外的HTML不一致。我已经看过无数无数的使用ng-bind-html的例子,如果我可以绑定到特定值,而不是动态值列表,我可以使用它。

这是我的第一个有角度的项目,所以我确信有一些简单的我不知道。我发布的代码正确呈现了html,但它只显示了多次的最后结果(我理解为什么)。

我怎样才能完成我想要做的事情?

这是我的玉码:

#search-main(ng-controller="autocomplete" data-api-url="/autocomplete.json")
  input(type="search" placeholder="Search" ng-model="termToComplete")
  input(type="image" name="submit" src="/search-icon.gif", alt="Submit")
  ul.autoSuggest(ng-if="items.length")
    li.fade-in(ng-repeat="item in items")
      h2: a(href="{{item.url}}" ng-bind-html="html")

以下是我的一些js

app.filter('html', ['$sce', function ($sce) { 
  return function (text) {
    return $sce.trustAsHtml(text);
  };    
}])

app.controller('autocomplete', function($scope, $element, $timeout, acAPIservice, $location, $sce){
  $scope.items = [];
  $scope.apiUrl = $element.attr('data-api-url');
  $scope.termToComplete = undefined;

  $scope.showSuggestion = function(){
  var payload = {
    term : $scope.termToComplete
  }

  acAPIservice.getSearch($scope.apiUrl, payload)
    .success(function(data){
      $scope.items = $scope.items.concat(data.results);
      $scope.findMatch();

   })
    .error(function(data, status, headers, config){      
      $scope.items = [];
   });
  }

  //iterates over the results and bolds matching terms
  $scope.findMatch = function(){
    var term = $scope.termToComplete;
    angular.forEach($scope.items, function(value, key){
    $scope.items[key].title = $sce.trustAsHtml($scope.items[key].title.replace(new RegExp('(^|)(' + term + ')(|$)','ig'), '$1<b>$2</b>$3'));
    $scope.html = $scope.items[key].title;
      });
   }


  $scope.$watch('termToComplete', function(newValue, oldValue) {
    // reset everything
    $scope.items = [];
    $scope.start = 0;
    $scope.end = 0;
    $scope.total = 0;
    // if we still have a search term go get it
    if($scope.termToComplete){
      $scope.showSuggestion();
    }
  });
});

这是我的测试-Json:

{
    "start" : 1,
    "end" : 8,
    "total" : 27,
    "results" : [{
        "id" : 0,
        "title" : "here is a title",
        "url" : "google.com"
    }, {
        "id" : 1,
        "title" : "here is another title",
        "url" : "google.com"
    }, {
        "id" : 2,
        "title" : "and another title",
        "url" : "google.com"
    }]
}

注意:

acAPIservice只是一个点击API并返回数据的工厂

1 个答案:

答案 0 :(得分:2)

您无需定义$scope.html,因为您已将HTML分配给title

您只需在ng-repeat循环中使用它:

li.fade-in(ng-repeat="item in items")
  h2: a(ng-href="{{item.url}}" ng-bind-html="item.title")

我还建议使用ng-href而不仅仅是href,因为您正在为链接使用角度表达式;)

相关问题