gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:05:05 25 4
gpt4 key购买 nike

以下工作:

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com