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

3
  • 1
    I hate to be a nitpicker, but you have 1 $scope in your controller with various variables, not various $scopes. Commented Oct 30, 2014 at 10:39
  • @popovitsj - thanks for the pointing that out, this is just an example. Commented Oct 30, 2014 at 10:40
  • Possible duplicate of Access scope variables from a filter in AngularJS Commented Mar 30, 2017 at 9:49

3 Answers 3

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]">
Sign up to request clarification or add additional context in comments.

2 Comments

Tried that, undefined is returned.
you have to pass the scope like myCustomFilter:this, if you need to pass only a one you can do like myCustomFilter:var1 .please check
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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.