我通过date这种方式将值传递给自定义过滤器:
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; } });
我也想在其中注入几个范围变量,就像我在指令中可以做的那样。不必将这些var作为函数参数显式传递就可以做到这一点吗?
显然可以。
通常,您会将范围变量作为函数参数传递给过滤器:
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:
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](http://plnkr.co/edit/8bHvoKVpACjFkgkP5iCn?p=preview)