我有controller
个$scopes
。我需要在自定义过滤器中访问其中一个$ scope:
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>
如何将$ scope.var1传递给我的myCustomFilter
??
答案 0 :(得分:5)
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]">
答案 1 :(得分:4)
您必须向过滤器提供所需的范围属性。
你可以这样做:
过滤强>
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>
答案 2 :(得分: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>