从AngularJS中的筛选器访问作用域变量



我通过以下方式将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;
    }
  });

我也想在那里注入几个范围变量,比如我可以在指令中做什么。这样做是否可能,而不必将这些变量显式地作为函数参数传递?

显然你可以。

通常,您会将范围变量作为函数参数传递给过滤器:

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>

CCD_ 3将参考当前范围:

简化:

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

柱塞

警告:

  1. 注意这一点,只使用scope来读取过滤器内的值,否则您将很容易在$digest循环中找到自己
  2. 需要这种";"重";依赖性(整个范围)往往很难测试

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

最新更新