2014-09-05 29 views
0

我有一个自定义过滤器返回匹配数组搜索字段输入,它的工作原理,但只有在导致无限$摘要循环后。这显然只是从Angular 1.0.6升级后才开始发生。这是在滤波代码:

angular.module("Directory.searches.filters", []) 
.filter('highlightMatches', function() { 
    var ary = []; 
    return function (obj, matcher) { 
    if (matcher && matcher.length) { 
     var regex = new RegExp("(\\w*" + matcher + "\\w*)", 'ig'); 
     ary.length = 0; 
     angular.forEach(obj, function (object) { 
     if (object.text.match(regex)) { 
      ary.push(angular.copy(object)); 
      ary[ary.length-1].text = object.text.replace(regex, "<em>$1</em>"); 
     } 
     }); 
     return ary; 
    } else { 
     return obj; 
    } 
    } 
}); 

具有的NG-显示内部的过滤器,我在其他地方看到,这可能引起,或者是因为返回的数组被解释为每一次新的数组这是检查,但我不知道如何解决这两个问题。您可以在https://www.popuparchive.com/collections/514/items/4859处看到此问题的生产示例,开放源代码项目位于https://github.com/PRX/pop-up-archive处。谢谢!

+0

你可以发布代码在哪里使用这个过滤器? – Prasad 2014-09-05 18:44:28

+1

我认为这是因为'angular.copy(object)'。每次摘要循环运行时,过滤器都会返回一个角度前所未见的新对象数组,因此摘要循环将永远持续。 – 2014-09-05 19:05:33

+1

@AnthonyChu谢谢!你有什么建议可以重构这个函数来避免这个问题吗? – Shindo 2014-09-06 00:54:25

回答

0

这是因为angular.copy(object)而发生的。每次摘要循环运行时,过滤器都会返回一个角度前所未见的新对象数组,因此摘要循环将永远持续。

一种解决方案是返回一个包含匹配过滤器的原始元素的数组,与添加到每个项目highlightedText属性...

angular.module("Directory.searches.filters", []) 
.filter('highlightMatches', function() { 
    return function (items, matcher) { 
    if (matcher && matcher.length) { 
     var filteredItems = []; 
     var regex = new RegExp("(\\w*" + matcher + "\\w*)", 'ig'); 
     angular.forEach(items, function (item) { 
     if (item.text.match(regex)) { 
      item.highlightedText = item.text.replace(regex, "<em>$1</em>"); 
      filteredItems.push(item); 
     } 
     }); 
     return filteredItems; 
    } else { 
     angular.forEach(items, function (item) { 
     item.highlightedText = item.text; 
     }); 
     return items; 
    } 
    } 
}); 

您可以绑定到highlightedText财产,像...

<div> 
    Results 
    <ul> 
     <li ng-repeat="item in items | highlightMatches : matcher" ng-bind-html="item.highlightedText"></li> 
    </ul> 
</div>