75

date以这种方式将值传递给我的自定义过滤器:

angular.module('myapp').
  filter('filterReceiptsForDate', function () {
    return function (input, date) {
      var out = _.filter(input, function (item) {
        return moment(item.value.created).format('YYYY-MM-DD') == date;
      });
      return out;
    }
  });

我也想在那里注入几个范围变量,就像我可以在指令中做的那样。是否可以在不必将这些变量作为函数参数显式传递的情况下做到这一点?

4

2 回答 2

126

显然你可以。

通常你会将作用域变量作为函数参数传递给过滤器:

function MyCtrl($scope){
  $scope.currentDate = new Date();
  $scope.dateFormat = 'short';
}
<span ng-controller="MyCtrl">{{currentDate | date:dateFormat}}</span> // --> 7/11/13 4:57 PM

但是,要传递当前范围,您必须通过this

<span ng-controller="MyCtrl">{{currentDate | date:this}}</span>

并将this作为对当前范围的引用:

简化:

app.controller('AppController',
    function($scope) {
      $scope.var1 = 'This is some text.';
      $scope.var2 = 'And this is appended with custom filter.';
    }
  );
  

app.filter('filterReceiptsForDate', function () {
  return function (input, scope) {
    return input + ' <strong>' + scope.var2 + '</strong>';
  };
});
<div ng-bind-html-unsafe="var1 | filterReceiptsForDate:this"></div>
<!-- Results in: "This is some text. <strong>And this is appended with custom filter.</strong>" -->

PLUNKER

警告:

  1. 请注意这一点并仅使用范围来读取过滤器内的值,否则您将很容易在 $digest 循环中找到自己。
  2. 需要这种“重”依赖(整个范围)的过滤器往往很难测试。
于 2013-07-11T15:07:30.940 回答
5

我发现this引用了 local $scope。不确定这是否是安全的访问方式。

于 2014-08-26T19:39:05.563 回答