问题
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"}]
回答1:
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);
});
回答2:
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
来源:https://stackoverflow.com/questions/28906953/filters-not-working-on-array-from-resource