自定义过滤器是否应该修改/更新其输入?

Should a custom filter modify / update its input?

假设我有一个像这样的自定义过滤器:

app.filter('custom', function () {
  return function (input, search) {

    const ret = {};

    // find matches in input, given search
    ret[key] = input[key] // etc etc

    return ret;

});

这是与过滤器一起使用的 HTML:

   <div class="row" ng-repeat="(promptId, q) in myHash | custom:searchText">

我认为我需要做的是,将控制器中的 myHash 设置为自定义过滤器中的 ret 值?

这是正确的做法吗?如果是,我该怎么做?

换句话说,我应该这样做吗:

   app.filter('custom', function ($scope) {
      return function (input, search) {

        const ret = {};

        // find matches in input, given search
        ret[key] = input[key] // etc etc

        return $scope.myHash = ret;   // do not do this LOL

    });

"[What] I believe I need to do, is set myHash in the controller to the ret value from the custom filter?"

不,那是错误的。过滤器不应修改其输入。它应该产生一个从输入派生的新值(即它的函数参数)。

来自AngularJS documentation on filters(重点是我加的):

"The filter function should be a pure function, which means that it should always return the same result given the same input arguments and should not affect external state."

据我所知,您已经在做正确的事情(在您的第一个代码示例中)。

令人惊讶的是,以下方法有效。

之前:

<div class="row" ng-repeat="(promptId, q) in myHash | custom:searchText">

之后:

 <div class="row" ng-repeat="(promptId, q) in (myFilteredHash = (myHash | custom:searchText))">

现在,我的控制器的 $scope 中有第二个变量,名为 myFilteredHash

您可以将 $scope 传递给过滤器,然后将 myFilteredHash 设置为结果。

我认为您不应该做的唯一一件事就是将原始值设置为过滤后的值,因为这样您基本上会丢失所有数据!最重要的是,您可能会为(无限)摘要循环设置自己。