1

I have a filter that is not returning anything when it is run on an array from a factory. But when I copy paste the array directly into the filter, it works fine. There must be a simple solution, and it is driving me crazy.

This works:

$filter('filter')([
  {"name":"firstItem","code":"one"},
  {"name":"secondItem","code":"two"},
  {"name":"thirdItem","code":"three"}
],"two",true);

This doesn't:

$filter('filter')($scope.items,"two",true);

Angular sample:

angular.module('App', ['ngResource'])

.controller('Ctrl', function($scope, $filter, Items) {
  $scope.items = Items.query();
  var codeToFilter = "two";
  $scope.badFilter = $filter('filter')($scope.items,codeToFilter,true);
  $scope.goodFilter = $filter('filter')([
    {"name":"firstItem","code":"one"},
    {"name":"secondItem","code":"two"},
    {"name":"thirdItem","code":"three"}
  ],"two",true);
})

.factory("Items", function ($resource) {
    return $resource("item-list.asp");
});

And the array returned from item-list.asp:

[{"name":"firstItem","code":"one"},{"name":"secondItem","code":"two"},{"name":"thirdItem","code":"three"}]

This is what I see on the page:

Bad Filter: []
Good Filter: [{"name":"secondItem","code":"two"}]

2 Answers 2

2

Items.query() is async and hence not resolved instantly. At the time your filter is hit, it's not populated.

Set it up like this:

Items.query(function(result) {
    $scope.items = result;
    $scope.badFilter = $filter('filter')($scope.items,codeToFilter,true);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response! Now I am getting TypeError: undefined is not a function on the Items.query line.
0

try this it adds in the array to the control to help pass in information to the function.

.controller('Ctrl', ['$scope', '$filter', 'Items', function($scope, $filter, Items) {

and then don't forget to close the square bracket after the functions close curly brace

2 Comments

This is exactly what he's doing except you've made it minification safe :)
I always wondered why we did that! I just know that's usually where my problems are. Still learning Angular glad your answer helps out.

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.