Search code examples
angularjsangularjs-scopeangular-filters

AngularJS - Access $scope from controller in custom filter


I have a controller with various $scopes. I need to access one of these $scopes in a custom filter:

app.controller('AppController',
    function($scope) {
      $scope.var1 = 'Some data1';
      $scope.var2 = 'Some data2';
    }
  );

app.filter('myCustomFilter', function ($filter) {

  return function (date) {
    var date = date;
  };
});


<tr ng-repeat="data in MyData" ng-class="{true: 'green', false:'red'}[data.Date | myCustomFilter]">

</tr>

How can i pass $scope.var1 into my myCustomFilter??


Solution

  • You must provide the wanted scope attribute to the filter.

    You can do it like that:

    Filter:

    app.filter('myCustomFilter', function ($filter) {
    
      return function (date,myVar1) {
    /* Do some stuff with myVar1 */
      };
    });
    

    HTML:

    <tr ng-repeat="data in MyData" ng-class="{true: 'green', false:'red'}[data.Date | myCustomFilter:var1]">
    
    </tr>