javascript - Access scope variables from a filter in AngularJS -


i passing date value custom filter 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 inject couple of scope variables there too, can in directives. possible without having passing these vars explicitly function arguments?

apparently can.

usually pass scope variables filter 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 

but, pass current scope in, you'd have pass this:

<span ng-controller="myctrl">{{currentdate | date:this}}</span> 

and this reference current scope:

simplified:

app.controller('appcontroller',     function($scope) {       $scope.var1 = 'this text.';       $scope.var2 = 'and appended 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 text. <strong>and appended custom filter.</strong>" --> 

plunker

warning:

  1. be careful , use scope read values inside filter, because otherwise find self in $digest loop.
  2. filters require such "heavy" dependency (the whole scope) tend difficult test.

Comments