Filters not working on array from resource

烈酒焚心 提交于 2019-12-24 14:28:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!