加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 过滤器可以是不纯的功能吗?

发布时间:2020-12-17 16:57:05 所属栏目:安全 来源:网络整理
导读:以下作品: scriptangular.module('myApp',[]).filter('myFilter',['$rootScope',function($rootScope) { return function(v) { return $rootScope.capitalize ? (v v.toUpperCase()) : v; };}]).controller('myController','$scope',function($rootScope,$s
以下作品:

<script>
angular.module('myApp',[])
.filter('myFilter',['$rootScope',function($rootScope) {
  return function(v) {
     return $rootScope.capitalize ? (v && v.toUpperCase()) : v;
  };
}])
.controller('myController','$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',function($rootScope) {
  var filter = function(v) {
     return $rootScope.capitalize ? (v && v.toUpperCase()) : v;
  };
  filter.$stateful = true;
  return filter;
}])

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读