3

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??

Oam Psy
  • 8,555
  • 32
  • 93
  • 157
  • 1
    I hate to be a nitpicker, but you have 1 $scope in your controller with various variables, not various $scopes. – wvdz Oct 30 '14 at 10:39
  • @popovitsj - thanks for the pointing that out, this is just an example. – Oam Psy Oct 30 '14 at 10:40
  • Possible duplicate of [Access scope variables from a filter in AngularJS](http://stackoverflow.com/questions/17596246/access-scope-variables-from-a-filter-in-angularjs) – Icarus Mar 30 '17 at 09:49

3 Answers3

6
app.filter('myCustomFilter', function ($filter) {
  return function (date, scope) {   // add scope here
    var date = date;
  };
});

ng-class="{true: 'green', false:'red'}[data.Date | myCustomFilter:this]">
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
4

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>
Julien
  • 2,256
  • 3
  • 26
  • 31
1

var app = angular.module('app', []);


app.controller('AppController',
  function($scope) {
    $scope.var1 = 2;
    $scope.var2 = 3;

    $scope.MyData = [{
      Date: 1
    }, {
      Date: 2
    }, {
      Date: 3
    }]

  }
);

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

  return function(date, scopeValue) {
    var date = date;
    return date * scopeValue
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body>
  <div ng-app="app">
    <div ng-controller="AppController">

      <li ng-repeat="data in MyData">
     Date:  {{data.Date}} | Date after myCustomFilter: {{data.Date | myCustomFilter : var1}}
      </li>
    </div>
  </div>


</body>
sylwester
  • 16,498
  • 1
  • 25
  • 33