从 AngularJS 中的过滤器访问范围变量 [英] Access scope variables from a filter in AngularJS

查看:25
本文介绍了从 AngularJS 中的过滤器访问范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am passing date value to my custom filter this way:

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;
    }
  });

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

I would like to inject a couple of scope variables there too, like what I can do in directives. Is that possible to do this without having to passing these vars explicitly as function arguments?

推荐答案

显然你可以.

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

Usually you would pass scope variables to the filter as function parameter:

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:

But, to pass the current scope in, you'd have to pass this:

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

this 将是对当前作用域的引用:

and this will be a reference to current scope:

简化:

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. 需要这种重"的过滤器依赖项(整个范围)往往很难测试.

这篇关于从 AngularJS 中的过滤器访问范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆