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"}]
psnoonan
  • 103
  • 1
  • 15

2 Answers2

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);
});
Tom
  • 7,640
  • 1
  • 23
  • 47
  • Thanks for the response! Now I am getting `TypeError: undefined is not a function` on the `Items.query` line. – psnoonan Mar 06 '15 at 20:39
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

Dan
  • 129
  • 8
  • 1
    This is exactly what he's doing except you've made it minification safe :) – Tom Mar 06 '15 at 20:31
  • 1
    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. – Dan Mar 06 '15 at 20:34