从AngularJS中的过滤器访问范围变量

Ser*_*rov 74 javascript scope 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;
    }
  });
Run Code Online (Sandbox Code Playgroud)

我想在那里注入几个范围变量,就像我在指令中可以做的那样.是否可以这样做而不必将这些变量显式地作为函数参数传递?

Ste*_*wie 122

显然你可以.

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

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

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

<span ng-controller="MyCtrl">{{currentDate | date:this}}</span>
Run Code Online (Sandbox Code Playgroud)

并将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>';
  };
});
Run Code Online (Sandbox Code Playgroud)
<div ng-bind-html-unsafe="var1 | filterReceiptsForDate:this"></div>
<!-- Results in: "This is some text. <strong>And this is appended with custom filter.</strong>" -->
Run Code Online (Sandbox Code Playgroud)

PLUNKER

警告:

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


小智 5

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