AngularJS 自定义过滤器何时执行?

When does AngularJS custom filters are executed?

我开发了一个自定义 AngularJS 过滤器,以便将来自数据库的带有换行符的文本格式化为 html 中的

我只有一页使用它而且只有一行:

<p class="info-section-body-text" ng-bind-html-unsafe="boatSelected.comments | htmlFormat"></p>

过滤器工作正常,但我注意到过滤器执行了 63 次。

为什么?我想从性能的角度来看这不是最好的。

AngualarJS 将在 UI、{{}}(插值)上评估 ng-ifng-showng-hideangular filter 等指令, ng-bind 等在每个摘要循环完成时进行评估,摘要循环的数量被调用 UI 级别的所有绑定都经过 angular 摘要循环。

我相信您使用的是早于 angular 的 1.2 版。(因为 ng-html-bind-unsafe 已被弃用)

如果你不想每次都调用 angular 过滤器,你可以使用 angular bindonce :: 指令,它只会绑定一次数据,永远不会 运行它的摘要循环。(你应该有 Angular 1.3+ 才能使用这个功能)

标记

<p class="info-section-body-text" 
   ng-bind-html="::trustedHtml(boatSelected.comments) | htmlFormat"></p>

代码

$scope.trustedHtml = function(comments){
   //inject ngSanitize module in app & add `$sce` on controller level
   return $sce.trustedHtml(comments); 
}