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

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

问题描述

我传递日期值设置为我定制的过滤器是这样的:

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

不过,通过当前的范围,你必须通过这个

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

这个将是当前范围中引用:

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. 小心这一点,使用范围为只读在过滤器内的值,否则你会很容易找到在$消化循环你的自我。

  2. 需要这样的重的依赖(全范围)过滤器往往是非常困难的考验。

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

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