2014-10-30 146 views
3

我有一個controller與各種$scopes。我需要訪問這些$範圍中的一個自定義過濾器:

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

+1

我討厭成爲nitpicker,但是你的控制器中有1 $ scope和各種變量,而不是各種$ scopes。 – wvdz 2014-10-30 10:39:20

+0

@popovitsj - 感謝指出,這只是一個例子。 – 2014-10-30 10:40:40

+0

[AngularJS中的過濾器訪問範圍變量]可能的副本(http://stackoverflow.com/questions/17596246/access-scope-variables-from-a-filter-in-angularjs) – Icarus 2017-03-30 09:49:29

回答

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> 
+0

謝謝! – 2014-10-30 10:49:35

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]"> 
+0

試過,未定義返回。 – 2014-10-30 10:41:01

+0

你必須通過**'myCustomFilter:this' **這樣的範圍,如果你只需要傳遞一個你可以像'myCustomFilter:var1'這樣的函數。請檢查 – 2014-10-30 10:50:57

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>

相關問題