Reputation: 8663
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
??
Upvotes: 3
Views: 15496
Reputation: 21911
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]">
Upvotes: 6
Reputation: 16508
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>
Upvotes: 1
Reputation: 2246
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>
Upvotes: 4