Search code examples
angularjsangular-filters

How can you use a controller $scope defined function in $filter


Please don't mistake this as the typical question on how to use $filter in a controller with an injected filter. My question has a slight nuance which is using a non-injected filter defined as a $scope property. For example, if you have this controller:

function MyCtrl($scope, $filter)
{
    $scope.itemsSource = [
        {id:1, name:'John'},
        {id:2, name:'Steve'},
        {id:'3', name:'Joey'},
        {id:4, name:'Mary'},
        {id:5, name:'Marylin'}];

    $scope.myFilter = function(){
        return function(val){
        return typeof val.id === 'number' 
      }
    };

    $scope.items = $filter('filter')($scope.itemsSource, $scope.myFilter);
};

What do I need to change in the $filter call to filter itemsSource using the $scope.myFilter function?

Here is a fiddle with a non-working example.


Solution

  • I don't know why you have that closure within your filter function.

    If you remove it and add a parameter, so your filter looks as follows, it works:

    $scope.myFilter = function(val){
        return typeof val.id === 'number' 
    };
    

    Here's an updated fiddle: http://jsfiddle.net/doc6c713/