angularjs - 过滤器可以是不纯的函数吗?

标签 angularjs

以下工作:

<script>
angular.module('myApp', [])
.filter('myFilter', ['$rootScope', function($rootScope) {
  return function(v) {
     return $rootScope.capitalize ? (v && v.toUpperCase()) : v;
  };
}])
.controller('myController', ['$rootScope', '$scope', function($rootScope, $scope) {
  $scope.flipCapitalize = function() {
    $rootScope.capitalize = !$rootScope.capitalize;
  }
}]);
</script>
{{"Hello" | myFilter }}

<div ng-controller="myController">
  <button ng-click="flipCapitalize()">flip</button>
</div>

当您按下按钮时,屏幕上的“Hello”一词会在混合大小写和大写之间切换。

但是 Angular 并不“知道”它应该重新调用过滤器函数。这样做只是因为单击会重新启动摘要外观并重新执行所有操作。

我的问题是:这种行为有保证吗?我是否可以始终假设过滤器将在摘要循环中重新调用,并且我可以在我能找到的任何范围内使用任何数据?还是我只是走运了?

我的第二个问题:如果在每个摘要循环上重新调用过滤器函数,有什么方法可以克服这种行为吗?我可以告诉它,除非参数改变,否则不要再次调用这个函数,你会得到相同的答案吗?还是我必须手动内存?

最佳答案

根据angular docs ,如果你想保证你的过滤器工作,你需要使用 $stateful 将其标记为“有状态”过滤器的属性。

It is strongly discouraged to write filters that are stateful, because the execution of those can't be optimized by Angular, which often leads to performance issues. Many stateful filters can be converted into stateless filters just by exposing the hidden state as a model and turning it into an argument for the filter.

If you however do need to write a stateful filter, you have to mark the filter as $stateful, which means that it will be executed one or more times during the each $digest cycle.


因此,您应该将过滤器标记为有状态以保证该行为:
.filter('myFilter', ['$rootScope', function($rootScope) {
  var filter = function(v) {
     return $rootScope.capitalize ? (v && v.toUpperCase()) : v;
  };
  filter.$stateful = true;
  return filter;
}])

关于angularjs - 过滤器可以是不纯的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707235/

相关文章:

javascript - Angular js 中的异步调用

javascript - 如何在 PhantomJS 测试中 ng-click A 指令

angularjs - 为什么添加额外的 AngularJS 验证指令会导致 $async Validators 运行多次?

javascript - angularjs ani-主题构建不起作用

angularjs - 如何在我的 Angular 应用程序中安装 underscore.js?

javascript - AngularJS:如何缓存从 $http 调用返回的 json 数据?

angularjs - Angular 多选下拉菜单 |按字母顺序排序

css - Angular - 在 ngAnimate 动画 View 时保持标题固定

javascript - 如何使图像上的跨度元素相对于图像大小调整?

javascript - 如何在 ui-sref 标记中放置重新加载选项